diff --git a/.github/workflows/ci-pr.yml b/.github/workflows/ci-pr.yml index 11ffc83f..98025a6f 100644 --- a/.github/workflows/ci-pr.yml +++ b/.github/workflows/ci-pr.yml @@ -76,7 +76,7 @@ jobs: MAVEN_OPTS="-X $MAVEN_OPTS" fi for module in $MODULES; do - if [[ "$module" == *"/"* ]]; then + if [[ "$module" == *"/"* ]]; then if [ "$FOLDERS" = "" ]; then FOLDERS="$module" else diff --git a/README.adoc b/README.adoc index ec988f7d..2965dd40 100644 --- a/README.adoc +++ b/README.adoc @@ -27,7 +27,7 @@ The following are the various components of this repository. |=== | `java.util.Supplier` | `java.util.Function` | `java.util.Consumer` -|link:functions/supplier/cdc-debezium-supplier/README.adoc[CDC Debezium] +|link:functions/supplier/debezium-supplier/README.adoc[Debezium supplier] |link:functions/function/aggregator-function/README.adoc[Aggregator] |link:functions/consumer/analytics-consumer/README.adoc[Analytics] @@ -113,7 +113,7 @@ The following are the various components of this repository. |=== | Source | Processor | Sink -|link:applications/source/cdc-debezium-source/README.adoc[CDC Debezium] +|link:applications/source/debezium-source/README.adoc[Debezium supplier] |link:applications/processor/aggregator-processor/README.adoc[Aggregator] |link:applications/sink/analytics-sink/README.adoc[Analytics] |link:applications/source/file-source/README.adoc[File] diff --git a/applications/source/cdc-debezium-source/README.adoc b/applications/source/cdc-debezium-source/README.adoc deleted file mode 100644 index 51511542..00000000 --- a/applications/source/cdc-debezium-source/README.adoc +++ /dev/null @@ -1,339 +0,0 @@ -//tag::ref-doc[] -= CDC Source - -https://en.wikipedia.org/wiki/Change_data_capture[Change Data Capture] (CDC) `source` that captures and streams change events from various databases. -Currently, it supports `MySQL`, `PostgreSQL`, `MongoDB`, `Oracle` and `SQL Server` databases. - -Build upon https://debezium.io/docs/embedded/[Debezium Embedded Connector], the `CDC Source` allows capturing and streaming database changes over different message binders such Apache Kafka, RabbitMQ and all Spring Cloud Stream supporter brokers. - -It supports all Debezium configuration properties. Just add the `cdc.config.` prefix to the existing Debezium properties. For example to set the Debezium's `connector.class` property use the `cdc.config.connector.class` source property instead. - -We provide convenient shortcuts for the most frequently used Debezium properties. For example instead of the long `cdc.config.connector.class=io.debezium.connector.mysql.MySqlConnector` Debezium property you can use our `cdc.connector=mysql` shortcut. The table below lists all available shortcuts along with the Debezium properties they represent. -The Debezium properties (e.g. `cdc.config.XXX`) always have precedence over the shortcuts! - -The CDC Source introduces a new default `BackingOffsetStore` configuration, based on the https://github.com/spring-cloud/stream-applications/blob/main/functions/common/metadata-store-common/README.adoc[MetadataStore] service. Later provides various microservices friendly ways for storing the offset metadata. - - -== Options - -//tag::configuration-properties[] -Properties grouped by prefix: - - -=== cdc - -$$config$$:: $$Spring pass-trough wrapper for debezium configuration properties. All properties with a 'cdc.config.' prefix are native Debezium properties. The prefix is removed, converting them into Debezium io.debezium.config.Configuration.$$ *($$Map$$, default: `$$$$`)* -$$connector$$:: $$Shortcut for the cdc.config.connector.class property. Either of those can be used as long as they do not contradict with each other.$$ *($$ConnectorType$$, default: `$$$$`, possible values: `mysql`,`postgres`,`mongodb`,`oracle`,`sqlserver`)* -$$name$$:: $$Unique name for this sourceConnector instance.$$ *($$String$$, default: `$$$$`)* -$$schema$$:: $$Include the schema's as part of the outbound message.$$ *($$Boolean$$, default: `$$false$$`)* - -=== cdc.flattening - -$$add-fields$$:: $$Comma separated list of metadata fields to add to the flattened message. The fields will be prefixed with "__" or "__[<]struct]__", depending on the specification of the struct.$$ *($$String$$, default: `$$$$`)* -$$add-headers$$:: $$Comma separated list specify a list of metadata fields to add to the header of the flattened message. The fields will be prefixed with "__" or "__[struct]__".$$ *($$String$$, default: `$$$$`)* -$$delete-handling-mode$$:: $$Options for handling deleted records: (1) none - pass the records through, (2) drop - remove the records and (3) rewrite - add a '__deleted' field to the records.$$ *($$DeleteHandlingMode$$, default: `$$$$`, possible values: `drop`,`rewrite`,`none`)* -$$drop-tombstones$$:: $$By default Debezium generates tombstone records to enable Kafka compaction on deleted records. The dropTombstones can suppress the tombstone records.$$ *($$Boolean$$, default: `$$true$$`)* -$$enabled$$:: $$Enable flattening the source record events (https://debezium.io/docs/configuration/event-flattening).$$ *($$Boolean$$, default: `$$true$$`)* - -=== cdc.offset - -$$commit-timeout$$:: $$Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt.$$ *($$Duration$$, default: `$$5000ms$$`)* -$$flush-interval$$:: $$Interval at which to try committing offsets. The default is 1 minute.$$ *($$Duration$$, default: `$$60000ms$$`)* -$$policy$$:: $$Offset storage commit policy.$$ *($$OffsetPolicy$$, default: `$$$$`)* -$$storage$$:: $$Kafka connector tracks the number processed records and regularly stores the count (as "offsets") in a preconfigured metadata storage. On restart the connector resumes the reading from the last recorded source offset.$$ *($$OffsetStorageType$$, default: `$$$$`, possible values: `memory`,`file`,`kafka`,`metadata`)* - -=== cdc.stream.header - -$$convert-connect-headers$$:: $$When true the {@link org.apache.kafka.connect.header.Header} are converted into message headers with the {@link org.apache.kafka.connect.header.Header#key()} as name and {@link org.apache.kafka.connect.header.Header#value()}.$$ *($$Boolean$$, default: `$$true$$`)* -$$offset$$:: $$Serializes the source record's offset metadata into the outbound message header under cdc.offset.$$ *($$Boolean$$, default: `$$false$$`)* - -=== metadata.store.dynamo-db - -$$create-delay$$:: $$Delay between create table retries.$$ *($$Integer$$, default: `$$1$$`)* -$$create-retries$$:: $$Retry number for create table request.$$ *($$Integer$$, default: `$$25$$`)* -$$read-capacity$$:: $$Read capacity on the table.$$ *($$Long$$, default: `$$1$$`)* -$$table$$:: $$Table name for metadata.$$ *($$String$$, default: `$$$$`)* -$$time-to-live$$:: $$TTL for table entries.$$ *($$Integer$$, default: `$$$$`)* -$$write-capacity$$:: $$Write capacity on the table.$$ *($$Long$$, default: `$$1$$`)* - -=== metadata.store.jdbc - -$$region$$:: $$Unique grouping identifier for messages persisted with this store.$$ *($$String$$, default: `$$DEFAULT$$`)* -$$table-prefix$$:: $$Prefix for the custom table name.$$ *($$String$$, default: `$$$$`)* - -=== metadata.store.mongo-db - -$$collection$$:: $$MongoDB collection name for metadata.$$ *($$String$$, default: `$$metadataStore$$`)* - -=== metadata.store.redis - -$$key$$:: $$Redis key for metadata.$$ *($$String$$, default: `$$$$`)* - -=== metadata.store - -$$type$$:: $$Indicates the type of metadata store to configure (default is 'memory'). You must include the corresponding Spring Integration dependency to use a persistent store.$$ *($$StoreType$$, default: `$$$$`, possible values: `mongodb`,`redis`,`dynamodb`,`jdbc`,`zookeeper`,`hazelcast`,`memory`)* - -=== metadata.store.zookeeper - -$$connect-string$$:: $$Zookeeper connect string in form HOST:PORT.$$ *($$String$$, default: `$$127.0.0.1:2181$$`)* -$$encoding$$:: $$Encoding to use when storing data in Zookeeper.$$ *($$Charset$$, default: `$$UTF-8$$`)* -$$retry-interval$$:: $$Retry interval for Zookeeper operations in milliseconds.$$ *($$Integer$$, default: `$$1000$$`)* -$$root$$:: $$Root node - store entries are children of this node.$$ *($$String$$, default: `$$/SpringIntegration-MetadataStore$$`)* -//end::configuration-properties[] - -==== Debezium property Shortcut mapping - -The table below lists all available shortcuts along with the Debezium properties they represent. - -.Table Shortcut Properties Mapping -|=== -| Shortcut | Original | Description - -|cdc.connector -|cdc.config.connector.class -|`mysql` : MySqlConnector, `postgres` : PostgresConnector, `mongodb` : MongodbSourceConnector, `oracle` : OracleConnector, `sqlserver` : SqlServerConnector - -|cdc.name -|cdc.config.name -| - -|cdc.offset.flush-interval -|cdc.config.offset.flush.interval.ms -| - -|cdc.offset.commit-timeout -|cdc.config.offset.flush.timeout.ms -| - -|cdc.offset.policy -|cdc.config.offset.commit.policy -|`periodic` : PeriodicCommitOffsetPolicy, `always` : AlwaysCommitOffsetPolicy - -|cdc.offset.storage -|cdc.config.offset.storage -|`metadata` : MetadataStoreOffsetBackingStore, `file` : FileOffsetBackingStore, `kafka` : KafkaOffsetBackingStore, `memory` : MemoryOffsetBackingStore - -|cdc.flattening.drop-tombstones -|cdc.config.drop.tombstones -| - -|cdc.flattening.delete-handling-mode -|cdc.config.delete.handling.mode -|`none` : none, `drop` : drop, `rewrite` : rewrite - -|=== - -== Database Support - -The `CDC Source` uses the Debezium utilities, and currently supports CDC for five datastores: `MySQL`, `PostgreSQL`, `MongoDB`, `Oracle` and `SQL Server` databases. - -== Examples and Testing - -The [CdcSourceIntegrationTest](), [CdcDeleteHandlingIntegrationTest]() and [CdcFlatteningIntegrationTest]() integration tests use test databases fixtures, running on the local machine. -We use pre-build debezium docker database images. -The Maven builds create the test databases fixtures with the help of the `docker-maven-plugin`. - -To run and debug the tests from your IDE you need to deploy the required database images from the command line. -Instructions below explains how to run pre-configured test databases form Docker images. - -==== MySQL - -Start the `debezium/example-mysql` in a docker: -[source, bash] ----- -docker run -it --rm --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=debezium -e MYSQL_USER=mysqluser -e MYSQL_PASSWORD=mysqlpw debezium/example-mysql:1.0 ----- - -[TIP] -==== -(optional) Use `mysql` client to connected to the database and to create a `debezium` user with required credentials: -[source, bash] ----- -docker run -it --rm --name mysqlterm --link mysql --rm mysql:5.7 sh -c 'exec mysql -h"$MYSQL_PORT_3306_TCP_ADDR" -P"$MYSQL_PORT_3306_TCP_PORT" -uroot -p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD"' -mysql> GRANT SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'debezium' IDENTIFIED BY 'dbz'; ----- -==== - -Use following properties to connect the CDC Source to MySQL DB: - -[source,properties] ----- -cdc.connector=mysql # <1> - -cdc.name=my-sql-connector # <2> -cdc.config.database.server.id=85744 # <2> -cdc.config.database.server.name=my-app-connector # <2> - -cdc.config.database.user=debezium # <3> -cdc.config.database.password=dbz # <3> -cdc.config.database.hostname=localhost # <3> -cdc.config.database.port=3306 # <3> - -cdc.schema=true # <4> -cdc.flattening.enabled=true # <5> ----- - -<1> Configures the CDC Source to use https://debezium.io/docs/connectors/mysql/[MySqlConnector]. (equivalent to setting `cdc.config.connector.class=io.debezium.connector.mysql.MySqlConnector`). -<2> Metadata used to identify and dispatch the incoming events. -<3> Connection to the MySQL server running on `localhost:3306` as `debezium` user. -<4> Includes the https://debezium.io/docs/connectors/mysql/#change-events-value[Change Event Value] schema in the `SourceRecord` events. -<5> Enables the https://debezium.io/docs/configuration/event-flattening/[CDC Event Flattening]. - -You can run also the `CdcSourceIntegrationTests#CdcMysqlTests` using this mysql configuration. - -==== PostgreSQL - -Start a pre-configured postgres server from the `debezium/example-postgres:1.0` Docker image: -[source, bash] ----- -docker run -it --rm --name postgres -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres debezium/example-postgres:1.0 ----- - -You can connect to this server like this: -[source, bash] ----- -psql -U postgres -h localhost -p 5432 ----- - -Use following properties to connect the CDC Source to PostgreSQL: - -[source,properties] ----- -cdc.connector=postgres # <1> -cdc.offset.storage=memory #<2> - -cdc.name=my-sql-connector # <3> -cdc.config.database.server.id=85744 # <3> -cdc.config.database.server.name=my-app-connector # <3> - -cdc.config.database.user=postgres # <4> -cdc.config.database.password=postgres # <4> -cdc.config.database..dbname=postgres # <4> -cdc.config.database.hostname=localhost # <4> -cdc.config.database.port=5432 # <4> - -cdc.schema=true # <5> -cdc.flattening.enabled=true # <6> ----- - -<1> Configures `CDC Source` to use https://debezium.io/docs/connectors/postgresql/[PostgresConnector]. Equivalent for setting `cdc.config.connector.class=io.debezium.connector.postgresql.PostgresConnector`. -<2> Configures the Debezium engine to use `memory` (e.g. `cdc.config.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore) backing offset store. -<3> Metadata used to identify and dispatch the incoming events. -<4> Connection to the PostgreSQL server running on `localhost:5432` as `postgres` user. -<5> Includes the https://debezium.io/docs/connectors/mysql/#change-events-value[Change Event Value] schema in the `SourceRecord` events. -<6> Enables the https://debezium.io/docs/configuration/event-flattening/[CDC Event Flattening]. - -You can run also the `CdcSourceIntegrationTests#CdcPostgresTests` using this mysql configuration. - -==== MongoDB - -Start a pre-configured mongodb from the `debezium/example-mongodb:0.10` Docker image: -[source, bash] ----- -docker run -it --rm --name mongodb -p 27017:27017 -e MONGODB_USER=debezium -e MONGODB_PASSWORD=dbz debezium/example-mongodb:0.10 ----- - -Initialize the inventory collections -[source, bash] ----- -docker exec -it mongodb sh -c 'bash -c /usr/local/bin/init-inventory.sh' ----- - -In the `mongodb` terminal output, search for a log entry like `host: "3f95a8a6516e:27017"` : -[source, bash] ----- -2019-01-10T13:46:10.004+0000 I COMMAND [conn1] command local.oplog.rs appName: "MongoDB Shell" command: replSetInitiate { replSetInitiate: { _id: "rs0", members: [ { _id: 0.0, host: "3f95a8a6516e:27017" } ] }, lsid: { id: UUID("5f477a16-d80d-41f2-9ab4-4ebecea46773") }, $db: "admin" } numYields:0 reslen:22 locks:{ Global: { acquireCount: { r: 36, w: 20, W: 2 }, acquireWaitCount: { W: 1 }, timeAcquiringMicros: { W: 312 } }, Database: { acquireCount: { r: 6, w: 4, W: 16 } }, Collection: { acquireCount: { r: 4, w: 2 } }, oplog: { acquireCount: { r: 2, w: 3 } } } protocol:op_msg 988ms ----- - -Add `127.0.0.1 3f95a8a6516e` entry to your `/etc/hosts` - - -Use following properties to connect the CDC Source to MongoDB: - -[source,properties] ----- -cdc.connector=mongodb # <1> -cdc.offset.storage=memory #<2> - -cdc.config.mongodb.hosts=rs0/localhost:27017 # <3> -cdc.config.mongodb.name=dbserver1 # <3> -cdc.config.mongodb.user=debezium # <3> -cdc.config.mongodb.password=dbz # <3> -cdc.config.database.whitelist=inventory # <3> - -cdc.config.tasks.max=1 # <4> - -cdc.schema=true # <5> -cdc.flattening.enabled=true # <6> ----- - -<1> Configures `CDC Source` to use https://debezium.io/docs/connectors/mongodb/[MongoDB Connector]. This maps into `cdc.config.connector.class=io.debezium.connector.mongodb.MongodbSourceConnector`. -<2> Configures the Debezium engine to use `memory` (e.g. `cdc.config.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore) backing offset store. -<3> Connection to the MongoDB running on `localhost:27017` as `debezium` user. -<4> https://debezium.io/docs/connectors/mongodb/#tasks -<5> Includes the https://debezium.io/docs/connectors/mysql/#change-events-value[Change Event Value] schema in the `SourceRecord` events. -<6> Enables the https://debezium.io/docs/configuration/event-flattening/[CDC Event Flattening]. - -You can run also the `CdcSourceIntegrationTests#CdcPostgresTests` using this mysql configuration. - -==== SQL Server - -Start a `sqlserver` from the `debezium/example-postgres:1.0` Docker image: -[source, bash] ----- -docker run -it --rm --name sqlserver -p 1433:1433 -e ACCEPT_EULA=Y -e MSSQL_PID=Standard -e SA_PASSWORD=Password! -e MSSQL_AGENT_ENABLED=true microsoft/mssql-server-linux:2017-CU9-GDR2 ----- - -Populate with sample data form debezium's sqlserver tutorial: -[source, bash] ----- -wget https://raw.githubusercontent.com/debezium/debezium-examples/master/tutorial/debezium-sqlserver-init/inventory.sql -cat ./inventory.sql | docker exec -i sqlserver bash -c '/opt/mssql-tools/bin/sqlcmd -U sa -P $SA_PASSWORD' ----- - -Use following properties to connect the CDC Source to SQLServer: - -[source,properties] ----- -cdc.connector=sqlserver # <1> -cdc.offset.storage=memory #<2> - -cdc.name=my-sql-connector # <3> -cdc.config.database.server.id=85744 # <3> -cdc.config.database.server.name=my-app-connector # <3> - -cdc.config.database.user=sa # <4> -cdc.config.database.password=Password! # <4> -cdc.config.database..dbname=testDB # <4> -cdc.config.database.hostname=localhost # <4> -cdc.config.database.port=1433 # <4> ----- - -<1> Configures `CDC Source` to use https://debezium.io/docs/connectors/sqlserver/[SqlServerConnector]. Equivalent for setting `cdc.config.connector.class=io.debezium.connector.sqlserver.SqlServerConnector`. -<2> Configures the Debezium engine to use `memory` (e.g. `cdc.config.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore) backing offset store. -<3> Metadata used to identify and dispatch the incoming events. -<4> Connection to the SQL Server running on `localhost:1433` as `sa` user. - -You can run also the `CdcSourceIntegrationTests#CdcSqlServerTests` using this mysql configuration. - -==== Oracle - -Start Oracle reachable from localhost and set up with the configuration, users and grants described in the https://github.com/debezium/oracle-vagrant-box[Debezium Vagrant set-up] - -Populate with sample data form Debezium's Oracle tutorial: -[source, bash] ----- -wget https://raw.githubusercontent.com/debezium/debezium-examples/master/tutorial/debezium-with-oracle-jdbc/init/inventory.sql -cat ./inventory.sql | docker exec -i dbz_oracle sqlplus debezium/dbz@//localhost:1521/ORCLPDB1 ----- - -//end::ref-doc[] - - -== Run standalone - -[source,shell] ----- -java -jar cdc-debezium-source.jar --cdc.connector=mysql --cdc.name=my-sql-connector --cdc.config.database.server.id=85744 --cdc.config.database.server.name=my-app-connector --cdc.config.database.user=debezium --cdc.config.database.password=dbz --cdc.config.database.hostname=localhost --cdc.config.database.port=3306 --cdc.schema=true --cdc.flattening.enabled=true ----- - diff --git a/applications/source/cdc-debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata-whitelist.properties b/applications/source/cdc-debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata-whitelist.properties deleted file mode 100644 index fa21a45a..00000000 --- a/applications/source/cdc-debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata-whitelist.properties +++ /dev/null @@ -1,12 +0,0 @@ -configuration-properties.classes=org.springframework.cloud.fn.supplier.cdc.CdcSupplierProperties, \ - org.springframework.cloud.fn.supplier.cdc.CdcSupplierProperties$Header, \ - org.springframework.cloud.fn.common.cdc.CdcCommonProperties, \ - org.springframework.cloud.fn.common.cdc.CdcCommonProperties$Flattening, \ - org.springframework.cloud.fn.common.cdc.CdcCommonProperties$Offset, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Gemfire, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Redis, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$DynamoDb, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Jdbc, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Zookeeper, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Mongo \ diff --git a/applications/source/cdc-debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata.properties b/applications/source/cdc-debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata.properties deleted file mode 100644 index fa21a45a..00000000 --- a/applications/source/cdc-debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata.properties +++ /dev/null @@ -1,12 +0,0 @@ -configuration-properties.classes=org.springframework.cloud.fn.supplier.cdc.CdcSupplierProperties, \ - org.springframework.cloud.fn.supplier.cdc.CdcSupplierProperties$Header, \ - org.springframework.cloud.fn.common.cdc.CdcCommonProperties, \ - org.springframework.cloud.fn.common.cdc.CdcCommonProperties$Flattening, \ - org.springframework.cloud.fn.common.cdc.CdcCommonProperties$Offset, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Gemfire, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Redis, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$DynamoDb, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Jdbc, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Zookeeper, \ - org.springframework.cloud.fn.common.metadata.store.MetadataStoreProperties$Mongo \ diff --git a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcDeleteHandlingIntegrationTest.java b/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcDeleteHandlingIntegrationTest.java deleted file mode 100644 index 5e930543..00000000 --- a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcDeleteHandlingIntegrationTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.stream.app.source.cdc; - -import java.time.Duration; -import java.util.List; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.testcontainers.junit.jupiter.Testcontainers; - -import org.springframework.boot.test.context.FilteredClassLoader; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.test.context.runner.ContextConsumer; -import org.springframework.cloud.fn.common.cdc.CdcCommonProperties; -import org.springframework.cloud.stream.binder.test.OutputDestination; -import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.kafka.support.KafkaNull; -import org.springframework.messaging.Message; -import org.springframework.test.jdbc.JdbcTestUtils; -import org.springframework.util.ClassUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.cloud.fn.supplier.cdc.CdcSupplierConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL; -import static org.springframework.cloud.stream.app.source.cdc.CdcTestUtils.CDC_SUPPLIER_OUT_0; -import static org.springframework.cloud.stream.app.source.cdc.CdcTestUtils.receiveAll; - -/** - * @author Christian Tzolov - * @author David Turanski - */ - -@Testcontainers -public class CdcDeleteHandlingIntegrationTest extends CdcMySqlTestSupport { - - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TestChannelBinderConfiguration.getCompleteConfiguration(TestCdcSourceApplication.class)) - .withPropertyValues( - "spring.cloud.function.definition=cdcSupplier", - "cdc.name=my-sql-connector", - "cdc.schema=false", - "cdc.flattening.enabled=true", - "cdc.stream.header.offset=true", - "cdc.connector=mysql", - "cdc.config.database.user=debezium", - "cdc.config.database.password=dbz", - "cdc.config.database.hostname=localhost", - "cdc.config.database.port=" + MAPPED_PORT, - // "cdc.config.database.server.id=85744", - "cdc.config.database.server.name=my-app-connector", - "cdc.config.database.history=io.debezium.relational.history.MemoryDatabaseHistory"); - - @ParameterizedTest - @ValueSource(strings = { - "cdc.flattening.deleteHandlingMode=none,cdc.flattening.dropTombstones=true", - "cdc.flattening.deleteHandlingMode=none,cdc.flattening.dropTombstones=false", - "cdc.flattening.deleteHandlingMode=drop,cdc.flattening.dropTombstones=true", - "cdc.flattening.deleteHandlingMode=drop,cdc.flattening.dropTombstones=false", - "cdc.flattening.deleteHandlingMode=rewrite,cdc.flattening.dropTombstones=true", - "cdc.flattening.deleteHandlingMode=rewrite,cdc.flattening.dropTombstones=false" - }) - public void handleRecordDeletions(String properties) { - contextRunner.withPropertyValues(properties.split(",")) - .withClassLoader(new FilteredClassLoader(KafkaNull.class)) // Remove Kafka from the - .run(consumer); - - contextRunner.withPropertyValues(properties.split(",")) - .run(consumer); - } - - private String toString(Object object) { - return new String((byte[]) object); - } - - final ContextConsumer consumer = context -> { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - - CdcCommonProperties props = context.getBean(CdcCommonProperties.class); - boolean isKafkaPresent = ClassUtils.isPresent(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, - context.getClassLoader()); - - CdcCommonProperties.DeleteHandlingMode deleteHandlingMode = props.getFlattening().getDeleteHandlingMode(); - boolean isDropTombstones = props.getFlattening().isDropTombstones(); - - jdbcTemplate.update( - "insert into `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); - String newRecordId = jdbcTemplate.query("select * from `customers` where `first_name` = ?", - (rs, rowNum) -> rs.getString("id"), "Test666").iterator().next(); - - List> messages = receiveAll(outputDestination); - assertThat(messages).hasSizeGreaterThanOrEqualTo(52); - - JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); - - Message received; - - if (deleteHandlingMode == CdcCommonProperties.DeleteHandlingMode.drop) { - // Do nothing - } - else if (deleteHandlingMode == CdcCommonProperties.DeleteHandlingMode.none) { - received = outputDestination.receive(Duration.ofSeconds(10).toMillis(), CDC_SUPPLIER_OUT_0); - assertThat(received).isNotNull(); - assertThat(received.getPayload()).isEqualTo("null".getBytes()); - } - else if (deleteHandlingMode == CdcCommonProperties.DeleteHandlingMode.rewrite) { - received = outputDestination.receive(Duration.ofSeconds(10).toMillis(), CDC_SUPPLIER_OUT_0); - assertThat(received).isNotNull(); - assertThat(toString(received.getPayload()).contains("\"__deleted\":\"true\"")); - } - - if (!isDropTombstones && isKafkaPresent) { - received = outputDestination.receive(Duration.ofSeconds(10).toMillis(), CDC_SUPPLIER_OUT_0); - assertThat(received).isNotNull(); - // Tombstones event should have KafkaNull payload - assertThat(received.getPayload().getClass().getCanonicalName()) - .isEqualTo(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL); - - String key = new String((byte[]) received.getHeaders().get("cdc_key")); - // Tombstones event should carry the deleted record id in the cdc_key header - assertThat(key).isEqualTo("{\"id\":" + newRecordId + "}"); - } - - received = outputDestination.receive(Duration.ofSeconds(1).toMillis(), CDC_SUPPLIER_OUT_0); - assertThat(received).isNull(); - }; -} diff --git a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcFlatteningIntegrationTest.java b/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcFlatteningIntegrationTest.java deleted file mode 100644 index 5f471caa..00000000 --- a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcFlatteningIntegrationTest.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2020-2021 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.stream.app.source.cdc; - -import java.util.List; - -import net.javacrumbs.jsonunit.core.Configuration; -import org.junit.jupiter.api.Test; - -import org.springframework.boot.test.context.FilteredClassLoader; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.boot.test.context.runner.ContextConsumer; -import org.springframework.cloud.fn.common.cdc.CdcCommonProperties; -import org.springframework.cloud.stream.binder.test.OutputDestination; -import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.kafka.support.KafkaNull; -import org.springframework.messaging.Message; -import org.springframework.test.jdbc.JdbcTestUtils; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.cloud.fn.supplier.cdc.CdcSupplierConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL; -import static org.springframework.cloud.stream.app.source.cdc.CdcTestUtils.receiveAll; -import static org.springframework.cloud.stream.app.source.cdc.CdcTestUtils.resourceToString; - -/** - * @author Christian Tzolov - * @author David Turanski - * @author Artem Bilan - */ -public class CdcFlatteningIntegrationTest extends CdcMySqlTestSupport { - - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration( - TestChannelBinderConfiguration.getCompleteConfiguration(TestCdcSourceApplication.class)) - .withPropertyValues( - "spring.cloud.function.definition=cdcSupplier", - "cdc.name=my-sql-connector", - "cdc.schema=false", - "cdc.stream.header.offset=false", - "cdc.connector=mysql", - "cdc.config.database.user=debezium", - "cdc.config.database.password=dbz", - "cdc.config.database.hostname=localhost", - "cdc.config.database.port=" + MAPPED_PORT, - // "cdc.config.database.server.id=85744", - "cdc.config.database.server.name=my-app-connector", - "cdc.config.database.history=io.debezium.relational.history.MemoryDatabaseHistory"); - - @Test - public void noFlattenedResponseNoKafka() { - contextRunner.withPropertyValues("cdc.flattening.enabled=false") - .withClassLoader(new FilteredClassLoader(KafkaNull.class)) // Remove Kafka from the classpath - .run(noFlatteningTest); - } - - @Test - public void noFlattenedResponseWithKafka() { - contextRunner.withPropertyValues("cdc.flattening.enabled=false") - .run(noFlatteningTest); - } - - final ContextConsumer noFlatteningTest = context -> { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - boolean isKafkaPresent = ClassUtils.isPresent(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, - context.getClassLoader()); - - List> messages = receiveAll(outputDestination); - assertThat(messages).hasSizeGreaterThanOrEqualTo(52); - - assertJsonEquals(resourceToString( - "classpath:/json/mysql_ddl_drop_inventory_address_table.json"), - toString(messages.get(1).getPayload()), - Configuration.empty().whenIgnoringPaths("schemaName", "tableChanges", "source.sequence", "source.ts_ms")); - assertThat(messages.get(1).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector"); - assertJsonEquals("{\"databaseName\":\"inventory\"}", toString(messages.get(1).getHeaders().get("cdc_key"))); - - assertJsonEquals(resourceToString("classpath:/json/mysql_insert_inventory_products_106.json"), - toString(messages.get(39).getPayload()), - Configuration.empty().whenIgnoringPaths("source.sequence", "source.ts_ms")); - assertThat(messages.get(39).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector.inventory.products"); - assertJsonEquals("{\"id\":106}", toString(messages.get(39).getHeaders().get("cdc_key"))); - - jdbcTemplate.update( - "insert into `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); - String newRecordId = jdbcTemplate.query("select * from `customers` where `first_name` = ?", - (rs, rowNum) -> rs.getString("id"), "Test666").iterator().next(); - jdbcTemplate.update("UPDATE `customers` SET `last_name`='Test999' WHERE first_name = 'Test666'"); - JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); - - messages = receiveAll(outputDestination); - - assertThat(messages).hasSize(isKafkaPresent ? 4 : 3); - - assertJsonEquals(resourceToString("classpath:/json/mysql_update_inventory_customers.json"), - toString(messages.get(1).getPayload()), Configuration.empty().whenIgnoringPaths("source.sequence")); - assertThat(messages.get(1).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector.inventory.customers"); - assertJsonEquals("{\"id\":" + newRecordId + "}", toString(messages.get(1).getHeaders().get("cdc_key"))); - - assertJsonEquals(resourceToString("classpath:/json/mysql_delete_inventory_customers.json"), - toString(messages.get(2).getPayload()), Configuration.empty().whenIgnoringPaths("source.sequence")); - assertThat(messages.get(1).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector.inventory.customers"); - - assertJsonEquals("{\"id\":" + newRecordId + "}", toString(messages.get(1).getHeaders().get("cdc_key"))); - - if (isKafkaPresent) { - assertThat(messages.get(3).getPayload().getClass().getCanonicalName()) - .isEqualTo(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, - "Tombstones event should have KafkaNull payload"); - assertThat(messages.get(3).getHeaders().get("cdc_topic")) - .isEqualTo("my-app-connector.inventory.customers"); - assertJsonEquals("{\"id\":" + newRecordId + "}", toString(messages.get(3).getHeaders().get("cdc_key"))); - } - }; - - @Test - public void flattenedResponseNoKafka() { - contextRunner.withPropertyValues( - "cdc.flattening.enabled=true", - "cdc.flattening.deleteHandlingMode=none", - "cdc.flattening.dropTombstones=false", - "cdc.flattening.addHeaders=op", - "cdc.flattening.addFields=name,db") - .withClassLoader(new FilteredClassLoader(KafkaNull.class)) // Remove Kafka from the classpath - .run(flatteningTest); - } - - @Test - public void flattenedResponseWithKafka() { - contextRunner.withPropertyValues( - "cdc.flattening.enabled=true", - "cdc.flattening.deleteHandlingMode=none", - "cdc.flattening.dropTombstones=false", - "cdc.flattening.addHeaders=op", - "cdc.flattening.addFields=name,db") - .run(flatteningTest); - } - - @Test - public void flattenedResponseWithKafkaDropTombstone() { - contextRunner.withPropertyValues( - "cdc.flattening.enabled=true", - "cdc.flattening.deleteHandlingMode=none", - "cdc.flattening.dropTombstones=true", - "cdc.flattening.addHeaders=op", - "cdc.flattening.addFields=name,db") - .run(flatteningTest); - } - - final ContextConsumer flatteningTest = context -> { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - boolean isKafkaPresent = ClassUtils.isPresent(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, - context.getClassLoader()); - - List> messages = receiveAll(outputDestination); - assertThat(messages).hasSizeGreaterThanOrEqualTo(52); - - CdcCommonProperties.Flattening flatteningProps = context.getBean(CdcCommonProperties.class).getFlattening(); - - assertJsonEquals(resourceToString( - "classpath:/json/mysql_ddl_drop_inventory_address_table.json"), - toString(messages.get(1).getPayload()), - Configuration.empty().whenIgnoringPaths("schemaName", "tableChanges", "source.sequence", "source.ts_ms")); - assertThat(messages.get(1).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector"); - assertJsonEquals("{\"databaseName\":\"inventory\"}", - toString(messages.get(1).getHeaders().get("cdc_key"))); - - if (flatteningProps.isEnabled()) { - assertJsonEquals(resourceToString("classpath:/json/mysql_flattened_insert_inventory_products_106.json"), - toString(messages.get(39).getPayload())); - } - else { - assertJsonEquals(resourceToString("classpath:/json/mysql_insert_inventory_products_106.json"), - toString(messages.get(39).getPayload())); - } - assertThat(messages.get(39).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector.inventory.products"); - assertJsonEquals("{\"id\":106}", toString(messages.get(39).getHeaders().get("cdc_key"))); - - if (flatteningProps.isEnabled() && flatteningProps.getAddHeaders().contains("op")) { - assertThat(messages.get(39).getHeaders().get("__op")).isEqualTo("r"); - } - - jdbcTemplate.update( - "insert into `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); - String newRecordId = jdbcTemplate.query("select * from `customers` where `first_name` = ?", - (rs, rowNum) -> rs.getString("id"), "Test666").iterator().next(); - jdbcTemplate.update("UPDATE `customers` SET `last_name`='Test999' WHERE first_name = 'Test666'"); - JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); - - messages = receiveAll(outputDestination); - - assertThat(messages).hasSize((!flatteningProps.isDropTombstones() && isKafkaPresent) ? 4 : 3); - - assertJsonEquals(resourceToString("classpath:/json/mysql_flattened_update_inventory_customers.json"), - toString(messages.get(1).getPayload())); - - assertThat(messages.get(1).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector.inventory.customers"); - assertJsonEquals("{\"id\":" + newRecordId + "}", toString(messages.get(1).getHeaders().get("cdc_key"))); - if (!StringUtils.isEmpty(flatteningProps.getAddHeaders()) && flatteningProps.getAddHeaders().contains("op")) { - assertThat(messages.get(1).getHeaders().get("__op")).isEqualTo("u"); - } - - if (flatteningProps.getDeleteHandlingMode() == CdcCommonProperties.DeleteHandlingMode.none) { - assertThat(toString(messages.get(2).getPayload())).isEqualTo("null"); - assertThat(messages.get(1).getHeaders().get("cdc_topic")).isEqualTo("my-app-connector.inventory.customers"); - assertJsonEquals("{\"id\":" + newRecordId + "}", toString(messages.get(1).getHeaders().get("cdc_key"))); - if (!StringUtils.isEmpty(flatteningProps.getAddHeaders()) - && flatteningProps.getAddHeaders().contains("op")) { - assertThat(messages.get(2).getHeaders().get("__op")).isEqualTo("d"); - } - } - - if (!flatteningProps.isDropTombstones() && isKafkaPresent) { - assertThat(messages.get(3).getPayload().getClass().getCanonicalName()) - .isEqualTo(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, - "Tombstones event should have KafkaNull payload"); - assertThat(messages.get(3).getHeaders().get("cdc_topic")) - .isEqualTo("my-app-connector.inventory.customers"); - assertJsonEquals("{\"id\":" + newRecordId + "}", toString(messages.get(3).getHeaders().get("cdc_key"))); - } - }; - - private String toString(Object object) { - return new String((byte[]) object); - } - -} diff --git a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcMySqlTestSupport.java b/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcMySqlTestSupport.java deleted file mode 100644 index a0a1e191..00000000 --- a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcMySqlTestSupport.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2020-2021 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.stream.app.source.cdc; - -import java.time.Duration; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Tag; -import org.testcontainers.containers.GenericContainer; - -import org.springframework.jdbc.core.JdbcTemplate; - -/** - * @author David Turanski - */ - -@Tag("integration") -public abstract class CdcMySqlTestSupport { - - static final String DATABASE_NAME = "inventory"; - - static String MAPPED_PORT; - - static GenericContainer debeziumMySQL = new GenericContainer<>("debezium/example-mysql:1.9.6.Final") - .withEnv("MYSQL_ROOT_PASSWORD", "debezium") - .withEnv("MYSQL_USER", "mysqluser") - .withEnv("MYSQL_PASSWORD", "mysqlpw") - // .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("mysql"))) - .withExposedPorts(3306) - .withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(3); - - static { - debeziumMySQL.start(); - } - - static JdbcTemplate jdbcTemplate; - - @BeforeAll - static void setup() { - MAPPED_PORT = String.valueOf(debeziumMySQL.getMappedPort(3306)); - jdbcTemplate = CdcTestUtils.jdbcTemplate( - "com.mysql.cj.jdbc.Driver", - "jdbc:mysql://localhost:" + MAPPED_PORT + "/" + DATABASE_NAME + "?enabledTLSProtocols=TLSv1.2", - "root", - "debezium"); - } -} diff --git a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcSourceDatabasesIntegrationTest.java b/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcSourceDatabasesIntegrationTest.java deleted file mode 100644 index d9b17ccd..00000000 --- a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcSourceDatabasesIntegrationTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2020-2022 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.stream.app.source.cdc; - -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.output.Slf4jLogConsumer; -import org.testcontainers.images.builder.ImageFromDockerfile; - -import org.springframework.boot.WebApplicationType; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.cloud.stream.binder.test.OutputDestination; -import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.messaging.Message; -import org.springframework.util.CollectionUtils; - -import static org.assertj.core.api.Assertions.assertThat; - - -/** - * @author Christian Tzolov - * @author David Turanski - * @author Artem Bilan - */ -@Tag("integration") -public class CdcSourceDatabasesIntegrationTest { - - - private static final String DEBEZIUM_EXAMPLE_MONGODB_1_9_6_FINAL = "debezium/example-mongodb:1.9.6.Final"; - - private static final String DEBEZIUM_EXAMPLE_POSTGRES_1_9_6_FINAL = "debezium/example-postgres:1.9.6.Final"; - - private static final String DEBEZIUM_EXAMPLE_MYSQL_1_9_6_FINAL = "debezium/example-mysql:1.9.6.Final"; - - private static final Log logger = LogFactory.getLog(CdcSourceDatabasesIntegrationTest.class); - - private final SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder( - TestChannelBinderConfiguration.getCompleteConfiguration(TestCdcSourceApplication.class)) - .web(WebApplicationType.NONE) - .properties("spring.cloud.function.definition=cdcSupplier", - "cdc.name=my-connector", - "cdc.flattening.dropTombstones=false", - "cdc.schema=false", - "cdc.flattening.enabled=true", - "cdc.stream.header.offset=true", - "cdc.config.database.server.name=my-app-connector", - "cdc.config.database.history=io.debezium.relational.history.MemoryDatabaseHistory"); - - @Test - public void mysql() { - GenericContainer debeziumMySQL = new GenericContainer<>(DEBEZIUM_EXAMPLE_MYSQL_1_9_6_FINAL) - .withEnv("MYSQL_ROOT_PASSWORD", "debezium") - .withEnv("MYSQL_USER", "mysqluser") - .withEnv("MYSQL_PASSWORD", "mysqlpw") - // .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("mysql"))) - .withExposedPorts(3306) - .withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(3); - debeziumMySQL.start(); - - String MAPPED_PORT = String.valueOf(debeziumMySQL.getMappedPort(3306)); - - try (ConfigurableApplicationContext context = applicationBuilder - .run("--cdc.connector=mysql", - "--cdc.config.database.user=debezium", - "--cdc.config.database.password=dbz", - "--cdc.config.database.hostname=localhost", - "--cdc.config.database.port=" + MAPPED_PORT)) { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - // Using local region here - List> messages = CdcTestUtils.receiveAll(outputDestination); - assertThat(messages).isNotNull(); - // Message size should correspond to the number of insert statements in the sample inventor DB configured in the debezium/example-mysql:1.9.6.Final: - // https://github.com/debezium/container-images/blob/main/examples/mysql/1.9/inventory.sql - assertThat(messages).hasSizeGreaterThanOrEqualTo(52); - } - } - - @Test - @Disabled - public void sqlServer() { - GenericContainer sqlServer = new GenericContainer(new ImageFromDockerfile() - .withFileFromClasspath("Dockerfile", "sqlserver/Dockerfile") - .withFileFromClasspath("import-data.sh", "sqlserver/import-data.sh") - .withFileFromClasspath("inventory.sql", "sqlserver/inventory.sql") - .withFileFromClasspath("entrypoint.sh", "sqlserver/entrypoint.sh")) - .withEnv("ACCEPT_EULA", "Y") - .withEnv("MSSQL_PID", "Standard") - .withEnv("SA_PASSWORD", "Password!") - .withEnv("MSSQL_AGENT_ENABLED", "true") - .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("sqlServer"))) - .withExposedPorts(1433) - .withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(3); - //sqlServer.waitingFor(Wait.forLogMessage(".*(1 rows affected).*", 50)).start(); - //sqlServer.waitingFor(Wait.forLogMessage(".*(Service Broker manager has started).*", 50)).start(); - sqlServer.start(); - - try (ConfigurableApplicationContext context = applicationBuilder - .run("--cdc.connector=sqlserver", - // "--cdc.config.database.user=Standard", - "--cdc.config.database.user=sa", - "--cdc.config.database.password=Password!", - "--cdc.config.database.dbname=testDB", - - "--cdc.config.database.hostname=localhost", - "--cdc.config.database.port=" + sqlServer.getMappedPort(1433))) { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - // Using local region here - List> messages = CdcTestUtils.receiveAll(outputDestination); - assertThat(messages).isNotNull(); - assertThat(messages).hasSize(30); - } - } - - @Test - public void postgres() { - GenericContainer postgres = new GenericContainer(DEBEZIUM_EXAMPLE_POSTGRES_1_9_6_FINAL) - .withEnv("POSTGRES_USER", "postgres") - .withEnv("POSTGRES_PASSWORD", "postgres") - .withExposedPorts(5432) - .withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(3); - postgres.start(); - - try (ConfigurableApplicationContext context = applicationBuilder - .run("--cdc.connector=postgres", - "--cdc.config.database.user=postgres", - "--cdc.config.database.password=postgres", - "--cdc.config.slot.name=debezium", - "--cdc.config.database.dbname=postgres", - "--cdc.config.database.hostname=localhost", - // "--cdc.config.table.include.list=inventory.*", - "--cdc.config.database.port=" + postgres.getMappedPort(5432))) { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - // Using local region here - - List> allMessages = new ArrayList<>(); - Awaitility.await().atMost(Duration.ofMinutes(5)).until(() -> { - List> messageChunk = CdcTestUtils.receiveAll(outputDestination); - if (!CollectionUtils.isEmpty(messageChunk)) { - logger.info("Chunk size: " + messageChunk.size()); - allMessages.addAll(messageChunk); - } - // Message size should correspond to the number of insert statements in the sample inventor DB configured in the debezium/example-postgres:1.9.6.Final: - // https://github.com/debezium/container-images/blob/main/examples/postgres/1.9/inventory.sql - return allMessages.size() == 29; // Inventory DB entries - }); - } - postgres.stop(); - } - - @Test - @Disabled - public void mongodb() { - GenericContainer mongodb = new GenericContainer(DEBEZIUM_EXAMPLE_MONGODB_1_9_6_FINAL) - .withEnv("MONGODB_USER", "debezium") - .withEnv("MONGODB_PASSWORD", "dbz") - .withExposedPorts(27017) - .withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(3); - mongodb.start(); - try (ConfigurableApplicationContext context = applicationBuilder - .run("--cdc.connector=mongodb", - "--cdc.config.tasks.max=1", - "--cdc.config.mongodb.hosts=rs0/localhost:" + mongodb.getMappedPort(27017), - "--cdc.config.mongodb.name=dbserver1", - "--cdc.config.mongodb.user=debezium", - "--cdc.config.mongodb.password=dbz", - "--cdc.config.collection.include.list=inventory[.]*")) { - OutputDestination outputDestination = context.getBean(OutputDestination.class); - // Using local region here - List> messages = CdcTestUtils.receiveAll(outputDestination); - assertThat(messages).isNotNull(); - assertThat(messages).hasSize(666); - } - mongodb.stop(); - } - -} diff --git a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/TestCdcSourceApplication.java b/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/TestCdcSourceApplication.java deleted file mode 100644 index e21b0a80..00000000 --- a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/TestCdcSourceApplication.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.stream.app.source.cdc; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; -import org.springframework.cloud.fn.supplier.cdc.CdcSupplierConfiguration; -import org.springframework.context.annotation.Import; - -/** - * @author Christian Tzolov - */ -@SpringBootConfiguration -@EnableAutoConfiguration(exclude = MongoAutoConfiguration.class) -@Import(CdcSupplierConfiguration.class) -public class TestCdcSourceApplication { -} diff --git a/applications/source/debezium-source/README.adoc b/applications/source/debezium-source/README.adoc new file mode 100644 index 00000000..8868a753 --- /dev/null +++ b/applications/source/debezium-source/README.adoc @@ -0,0 +1,340 @@ +//tag::ref-doc[] += Debezium Source + +https://debezium.io/documentation/reference/2.2/development/engine.html[Debezium Engine] based https://en.wikipedia.org/wiki/Change_data_capture[Change Data Capture] (CDC) source. +The `Debezium Source` allows *capturing* database change events and *streaming* those over different message binders such `Apache Kafka`, `RabbitMQ` and all Spring Cloud Stream supporter brokers. + +NOTE: This source can be used with *any* Spring Cloud Stream message binder. +It is not restricted nor depended on the Kafka Connect framework. Though this approach is flexible it comes with certain https://debezium.io/documentation/reference/2.2/development/engine.html#_handling_failures[limitations]. + +All Debezium configuration properties are supported. +Just precede any Debezium properties with the `debezium.properties.` prefix. +For example to set the Debezium's `connector.class` property use the `debezium.properties.connector.class` source property instead. + +== Database Support + +The `Debezium Source` currently supports CDC for multiple datastores: https://debezium.io/documentation/reference/2.2/connectors/mysql.html[MySQL], https://debezium.io/documentation/reference/2.2/connectors/postgresql.html[PostgreSQL], https://debezium.io/documentation/reference/2.2/connectors/mongodb.html[MongoDB], https://debezium.io/documentation/reference/2.2/connectors/oracle.html[Oracle], https://debezium.io/documentation/reference/2.2/connectors/sqlserver.html[SQL Server], https://debezium.io/documentation/reference/2.2/connectors/db2.html[Db2], https://debezium.io/documentation/reference/2.2/connectors/vitess.html[Vitess] and https://debezium.io/documentation/reference/2.2/connectors/spanner.html[Spanner] databases. + +== Options + +//tag::configuration-properties[] +$$debezium.copy-headers$$:: $$Copy Change Event headers into Message headers.$$ *($$Boolean$$, default: `$$true$$`)* +$$debezium.debezium-native-configuration$$:: $$$$ *($$Properties$$, default: `$$$$`)* +$$debezium.format$$:: $$Change Event message content format. Defaults to 'JSON'.$$ *($$DebeziumFormat$$, default: `$$$$`, possible values: `JSON`,`AVRO`,`PROTOBUF`)* +$$debezium.offset-commit-policy$$:: $$The policy that defines when the offsets should be committed to offset storage.$$ *($$DebeziumOffsetCommitPolicy$$, default: `$$$$`, possible values: `ALWAYS`,`PERIODIC`,`DEFAULT`)* +$$debezium.properties$$:: $$Spring pass-trough wrapper for debezium configuration properties. All properties with a 'debezium.properties.*' prefix are native Debezium properties.$$ *($$Map$$, default: `$$$$`)* +//end::configuration-properties[] + +==== Event flattening configuration + +Debezium provides a comprehensive message format, that accurately details information about changes that happen in the system. +Sometime this format, though, might not be suitable for the downstream consumers, that might require messages that are formatted so that field names and values are presented in a simplified, `flattened` structure. + +To simplify the format of the event records that the Debezium connectors produce, you can use the https://debezium.io/documentation/reference/stable/transformations/event-flattening.html[Debezium event flattening] message transformation. +Using the https://debezium.io/documentation/reference/stable/transformations/event-flattening.html#_configuration[flattering configuration] you can configure simple messages format like this: + +[source, bash] +---- +--debezium.properties.transforms=unwrap +--debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState +--debezium.properties.transforms.unwrap.drop.tombstones=false +--debezium.properties.transforms.unwrap.delete.handling.mode=rewrite +--debezium.properties.transforms.unwrap.add.fields=name,db +---- + +==== Connectors properties + +The table below lists all available Debezium properties for each connecter. +Those properties can be used by prefixing them by the `debezium.properties.` prefix. + +.Table of the configuration properties for every Debezium connector. +|=== +| Connector | Connector properties + +|https://debezium.io/documentation/reference/2.2/connectors/mysql.html[MySQL] +|https://debezium.io/documentation/reference/2.2/connectors/mysql.html#mysql-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/mongodb.html[MongoDB] +|https://debezium.io/documentation/reference/2.2/connectors/mongodb.html#mongodb-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/postgresql.html[PostgreSQL] +|https://debezium.io/documentation/reference/2.2/connectors/postgresql.html#postgresql-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/oracle.html[Oracle] +|https://debezium.io/documentation/reference/2.2/connectors/oracle.html#oracle-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/sqlserver.html[SQL Server] +|https://debezium.io/documentation/reference/2.2/connectors/sqlserver.html#sqlserver-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/db2.html[DB2] +|https://debezium.io/documentation/reference/2.2/connectors/db2.html#db2-connector-properties + +// |https://debezium.io/documentation/reference/2.2/connectors/cassandra.html[Cassandra] +// |https://debezium.io/documentation/reference/2.2/connectors/cassandra.html#cassandra-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/vitess.html[Vitess] +|https://debezium.io/documentation/reference/2.2/connectors/vitess.html#vitess-connector-properties + +|https://debezium.io/documentation/reference/2.2/connectors/spanner.html[Spanner] +|https://debezium.io/documentation/reference/2.2/connectors/spanner.html#spanner-connector-properties + +|=== + +== Examples and Testing + +The debezium integration tests use databases fixtures, running on the local machine. Pre-build debezium docker database images with the help of Testcontainers are leveraged. + +To run and debug the tests from your IDE you need to deploy the required database images from the command line. +Instructions below explains how to run pre-configured test databases form Docker images. + +==== MySQL + +Start the `debezium/example-mysql` in a docker: +[source, bash] +---- +docker run -it --rm --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=debezium -e MYSQL_USER=mysqluser -e MYSQL_PASSWORD=mysqlpw debezium/example-mysql:2.2.0.Final +---- + +[TIP] +==== +(optional) Use `mysql` client to connected to the database and to create a `debezium` user with required credentials: +[source, bash] +---- +docker run -it --rm --name mysqlterm --link mysql --rm mysql:5.7 sh -c 'exec mysql -h"$MYSQL_PORT_3306_TCP_ADDR" -P"$MYSQL_PORT_3306_TCP_PORT" -uroot -p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD"' +mysql> GRANT SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'debezium' IDENTIFIED BY 'dbz'; +---- +==== + +Use following properties to connect the Debezium Source to MySQL DB: + +[source,properties] +---- +debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector # <1> + +debezium.properties.topic.prefix=my-topic # <2> +debezium.properties.name=my-connector # <2> +debezium.properties.database.server.id=85744 # <2> +debezium.properties.database.server.name=my-app-connector # <2> + +debezium.properties.database.user=debezium # <3> +debezium.properties.database.password=dbz # <3> +debezium.properties.database.hostname=localhost # <3> +debezium.properties.database.port=3306 # <3> + +debezium.properties.schema=true # <4> +debezium.properties.key.converter.schemas.enable=true # <4> +debezium.properties.value.converter.schemas.enable=true # <4> + +debezium.properties.transforms=unwrap # <5> +debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState # <5> +debezium.properties.transforms.unwrap.add.fields=name,db # <5> +debezium.properties.transforms.unwrap.delete.handling.mode=none # <5> +debezium.properties.transforms.unwrap.drop.tombstones=true # <5> + +debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory # <6> +debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory # <6> +debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore # <6> + +---- + +<1> Configures the Debezium Source to use https://debezium.io/docs/connectors/mysql/[MySqlConnector]. +<2> Metadata used to identify and dispatch the incoming events. +<3> Connection to the MySQL server running on `localhost:3306` as `debezium` user. +<4> Includes the https://debezium.io/docs/connectors/mysql/#change-events-value[Change Event Value] schema in the `ChangeEvent` message. +<5> Enables the https://debezium.io/documentation/reference/2.2/transformations/event-flattening.html[Change Event Flattening]. +<6> Source state to preserver between multiple starts. + +You can run also the `DebeziumDatabasesIntegrationTest#mysql()` using this mysql configuration. + +NOTE: Disable the mysql GenericContainer test initialization code. + + +==== PostgreSQL + +Start a pre-configured postgres server from the `debezium/example-postgres:1.0` Docker image: +[source, bash] +---- +docker run -it --rm --name postgres -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres debezium/example-postgres:2.2.0.Final +---- + +You can connect to this server like this: +[source, bash] +---- +psql -U postgres -h localhost -p 5432 +---- + +Use following properties to connect the Debezium Source to PostgreSQL: + +[source,properties] +---- +debezium.properties.connector.class=io.debezium.connector.postgresql.PostgresConnector # <1> + +debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory # <2> +debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory # <2> +debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore # <2> + +debezium.properties.topic.prefix=my-topic # <3> +debezium.properties.name=my-connector # <3> +debezium.properties.database.server.id=85744 # <3> +debezium.properties.database.server.name=my-app-connector # <3> + +debezium.properties.database.user=postgres # <4> +debezium.properties.database.password=postgres # <4> +debezium.properties.database..dbname=postgres # <4> +debezium.properties.database.hostname=localhost # <4> +debezium.properties.database.port=5432 # <4> + +debezium.properties.schema=true # <5> +debezium.properties.key.converter.schemas.enable=true # <5> +debezium.properties.value.converter.schemas.enable=true # <5> + +debezium.properties.transforms=unwrap # <6> +debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState # <6> +debezium.properties.transforms.unwrap.add.fields=name,db # <6> +debezium.properties.transforms.unwrap.delete.handling.mode=none # <6> +debezium.properties.transforms.unwrap.drop.tombstones=true # <6> +---- + +<1> Configures `Debezium Source` to use https://debezium.io/docs/connectors/postgresql/[PostgresConnector]. +<2> Configures the Debezium engine to use `memory` stores. +<3> Metadata used to identify and dispatch the incoming events. +<4> Connection to the PostgreSQL server running on `localhost:5432` as `postgres` user. +<5> Includes the https://debezium.io/docs/connectors/mysql/#change-events-value[Change Event Value] schema in the message. +<6> Enables the https://debezium.io/docs/configuration/event-flattening/[Chage Event Flattening]. + +You can run also the `DebeziumDatabasesIntegrationTest#postgres()` using this postgres configuration. + +NOTE: Disable the postgres GenericContainer test initialization code. + +==== MongoDB + +Start a pre-configured mongodb from the `debezium/example-mongodb:2.2.0.Final` container image: +[source, bash] +---- +docker run -it --rm --name mongodb -p 27017:27017 -e MONGODB_USER=debezium -e MONGODB_PASSWORD=dbz debezium/example-mongodb:2.2.0.Final +---- + +Initialize the inventory collections +[source, bash] +---- +docker exec -it mongodb sh -c 'bash -c /usr/local/bin/init-inventory.sh' +---- + +In the `mongodb` terminal output, search for a log entry like `host: "3f95a8a6516e:27017"` : +[source, bash] +---- +2019-01-10T13:46:10.004+0000 I COMMAND [conn1] command local.oplog.rs appName: "MongoDB Shell" command: replSetInitiate { replSetInitiate: { _id: "rs0", members: [ { _id: 0.0, host: "3f95a8a6516e:27017" } ] }, lsid: { id: UUID("5f477a16-d80d-41f2-9ab4-4ebecea46773") }, $db: "admin" } numYields:0 reslen:22 locks:{ Global: { acquireCount: { r: 36, w: 20, W: 2 }, acquireWaitCount: { W: 1 }, timeAcquiringMicros: { W: 312 } }, Database: { acquireCount: { r: 6, w: 4, W: 16 } }, Collection: { acquireCount: { r: 4, w: 2 } }, oplog: { acquireCount: { r: 2, w: 3 } } } protocol:op_msg 988ms +---- + +Add `127.0.0.1 3f95a8a6516e` entry to your `/etc/hosts` + +Use following properties to connect the Debezium Source to MongoDB: + +[source,properties] +---- +debezium.properties.connector.class=io.debezium.connector.mongodb.MongodbSourceConnector # <1> + +debezium.properties.topic.prefix=my-topic +debezium.properties.name=my-connector +debezium.properties.database.server.id=85744 +debezium.properties.database.server.name=my-app-connector + +debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory # <2> +debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory # <2> +debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore # <2> + +debezium.properties.mongodb.hosts=rs0/localhost:27017 # <3> +debezium.properties.mongodb.name=dbserver1 # <3> +debezium.properties.mongodb.user=debezium # <3> +debezium.properties.mongodb.password=dbz # <3> +debezium.properties.database.whitelist=inventory # <3> + +debezium.properties.tasks.max=1 # <4> + +debezium.properties.schema=true # <5> +debezium.properties.key.converter.schemas.enable=true # <5> +debezium.properties.value.converter.schemas.enable=true # <5> + +debezium.properties.transforms=unwrap # <6> +debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState # <6> +debezium.properties.transforms.unwrap.add.fields=name,db # <6> +debezium.properties.transforms.unwrap.delete.handling.mode=none # <6> +debezium.properties.transforms.unwrap.drop.tombstones=true # <6> +---- + +<1> Configures `Debezium Source` to use https://debezium.io/docs/connectors/mongodb/[MongoDB Connector]. +<2> Configures the Debezium engine to use `memory`. +<3> Connection to the MongoDB running on `localhost:27017` as `debezium` user. +<4> https://debezium.io/docs/connectors/mongodb/#tasks +<5> Includes the https://debezium.io/docs/connectors/mysql/#change-events-value[Change Event Value] schema in the `SourceRecord` events. +<6> Enables the https://debezium.io/docs/configuration/event-flattening/[Chnage Event Flattening]. + +You can run also the `DebeziumDatabasesIntegrationTest#mongodb()` using this mongodb configuration. + +==== SQL Server + +Start a `sqlserver` from the `debezium/example-postgres:1.0` Docker image: +[source, bash] +---- +docker run -it --rm --name sqlserver -p 1433:1433 -e ACCEPT_EULA=Y -e MSSQL_PID=Standard -e SA_PASSWORD=Password! -e MSSQL_AGENT_ENABLED=true microsoft/mssql-server-linux:2017-CU9-GDR2 +---- + +Populate with sample data form debezium SqlServer tutorial: +[source, bash] +---- +wget https://raw.githubusercontent.com/debezium/debezium-examples/master/tutorial/debezium-sqlserver-init/inventory.sql +cat ./inventory.sql | docker exec -i sqlserver bash -c '/opt/mssql-tools/bin/sqlcmd -U sa -P $SA_PASSWORD' +---- + +Use following properties to connect the Debezium Source to SQLServer: + +[source,properties] +---- +debezium.properties.connector.class=io.debezium.connector.sqlserver.SqlServerConnector # <1> + +debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory # <2> +debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory # <2> +debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore # <2> + +debezium.properties.topic.prefix=my-topic # <3> +debezium.properties.name=my-connector # <3> +debezium.properties.database.server.id=85744 # <3> +debezium.properties.database.server.name=my-app-connector # <3> + +debezium.properties.database.user=sa # <4> +debezium.properties.database.password=Password! # <4> +debezium.properties.database..dbname=testDB # <4> +debezium.properties.database.hostname=localhost # <4> +debezium.properties.database.port=1433 # <4> +---- + +<1> Configures `Debezium Source` to use https://debezium.io/docs/connectors/sqlserver/[SqlServerConnector]. +<2> Configures the Debezium engine to use `memory` state stores. +<3> Metadata used to identify and dispatch the incoming events. +<4> Connection to the SQL Server running on `localhost:1433` as `sa` user. + +You can run also the `DebeziumDatabasesIntegrationTest#sqlServer()` using this SqlServer configuration. + +==== Oracle + +Start Oracle reachable from localhost and set up with the configuration, users and grants described in the https://github.com/debezium/oracle-vagrant-box[Debezium Vagrant set-up] + +Populate with sample data form Debezium Oracle tutorial: +[source, bash] +---- +wget https://raw.githubusercontent.com/debezium/debezium-examples/master/tutorial/debezium-with-oracle-jdbc/init/inventory.sql +cat ./inventory.sql | docker exec -i dbz_oracle sqlplus debezium/dbz@//localhost:1521/ORCLPDB1 +---- + + +//end::ref-doc[] + + +== Run standalone + +[source,shell] +---- +java -jar debezium-source.jar --debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector --debezium.properties.topic.prefix=my-topic --debezium.properties.name=my-connector --debezium.properties.database.server.id=85744 --debezium.properties.database.server.name=my-app-connector --debezium.properties.database.server.id=85744 --debezium.properties.database.server.name=my-app-connector --debezium.properties.database.user=debezium --debezium.properties.database.password=dbz --debezium.properties.database.hostname=localhost --debezium.properties.database.port=3306 --debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory --debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory --debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore +---- + + diff --git a/applications/source/cdc-debezium-source/pom.xml b/applications/source/debezium-source/pom.xml similarity index 65% rename from applications/source/cdc-debezium-source/pom.xml rename to applications/source/debezium-source/pom.xml index 3a072b35..e0664a7d 100644 --- a/applications/source/cdc-debezium-source/pom.xml +++ b/applications/source/debezium-source/pom.xml @@ -1,6 +1,6 @@ - + 4.0.0 @@ -12,20 +12,22 @@ 1.25.1 - 8.0.13 + - cdc-debezium-source - cdc-debezium-source - CDC Debezium source apps + debezium-source + debezium-source + Debezium source apps jar org.springframework.cloud.fn - cdc-debezium-supplier + debezium-supplier ${java-functions.version} + + org.springframework.cloud.fn function-test-support @@ -84,7 +86,40 @@ mysql test - + + com.zaxxer + HikariCP + 4.0.3 + test + + + org.eclipse.jetty + jetty-server + 11.0.14 + test + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + test + + + org.springframework.cloud + spring-cloud-stream-test-binder + test + + + mysql + mysql-connector-java + 8.0.33 + test + + + io.debezium + debezium-testing-testcontainers + 2.2.0.Final + @@ -106,22 +141,22 @@ spring-cloud-dataflow-apps-generator-plugin - cdc-debezium + debezium source ${project.version} - org.springframework.cloud.fn.supplier.cdc.CdcSupplierConfiguration.class + org.springframework.cloud.fn.supplier.debezium.DebeziumReactiveConsumerConfiguration.class - cdcSupplier + debeziumSupplier org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration - headers['cdc_key'] + headers['debezium_key'] org.springframework.cloud.fn - cdc-debezium-supplier + debezium-supplier diff --git a/applications/source/debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata-whitelist.properties b/applications/source/debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata-whitelist.properties new file mode 100644 index 00000000..6fa81eab --- /dev/null +++ b/applications/source/debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata-whitelist.properties @@ -0,0 +1 @@ +configuration-properties.classes=org.springframework.cloud.fn.supplier.debezium.DebeziumProperties diff --git a/applications/source/debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata.properties b/applications/source/debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata.properties new file mode 100644 index 00000000..6fa81eab --- /dev/null +++ b/applications/source/debezium-source/src/main/resources/META-INF/dataflow-configuration-metadata.properties @@ -0,0 +1 @@ +configuration-properties.classes=org.springframework.cloud.fn.supplier.debezium.DebeziumProperties diff --git a/applications/source/debezium-source/src/main/resources/application.properties b/applications/source/debezium-source/src/main/resources/application.properties new file mode 100644 index 00000000..5c60255b --- /dev/null +++ b/applications/source/debezium-source/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.cloud.stream.kafka.default.producer.messageKeyExpression=headers['debezium_key'].bytes diff --git a/applications/source/cdc-debezium-source/src/test/docker/mongodb/Dockerfile b/applications/source/debezium-source/src/test/docker/mongodb/Dockerfile similarity index 100% rename from applications/source/cdc-debezium-source/src/test/docker/mongodb/Dockerfile rename to applications/source/debezium-source/src/test/docker/mongodb/Dockerfile diff --git a/applications/source/cdc-debezium-source/src/test/docker/mongodb/entrypoint.sh b/applications/source/debezium-source/src/test/docker/mongodb/entrypoint.sh similarity index 100% rename from applications/source/cdc-debezium-source/src/test/docker/mongodb/entrypoint.sh rename to applications/source/debezium-source/src/test/docker/mongodb/entrypoint.sh diff --git a/applications/source/cdc-debezium-source/src/test/docker/mongodb/import-data.sh b/applications/source/debezium-source/src/test/docker/mongodb/import-data.sh similarity index 100% rename from applications/source/cdc-debezium-source/src/test/docker/mongodb/import-data.sh rename to applications/source/debezium-source/src/test/docker/mongodb/import-data.sh diff --git a/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/databases/DebeziumDatabasesIntegrationTest.java b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/databases/DebeziumDatabasesIntegrationTest.java new file mode 100644 index 00000000..c0223d41 --- /dev/null +++ b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/databases/DebeziumDatabasesIntegrationTest.java @@ -0,0 +1,214 @@ +/* + * Copyright 2020-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.stream.app.source.debezium.databases; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import io.debezium.testing.testcontainers.MongoDbContainer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.utility.DockerImageName; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.cloud.fn.supplier.debezium.DebeziumReactiveConsumerConfiguration; +import org.springframework.cloud.stream.app.source.debezium.integration.DebeziumTestUtils; +import org.springframework.cloud.stream.binder.test.OutputDestination; +import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Import; +import org.springframework.messaging.Message; +import org.springframework.util.CollectionUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests integration with supported Debezium connector datastores. It uses the Debezium pre-build example-images for + * those datastores and pre-generated data for them. + * + * @author Christian Tzolov + * @author David Turanski + * @author Artem Bilan + */ +@Tag("integration") +public class DebeziumDatabasesIntegrationTest { + + private static final Log logger = LogFactory.getLog(DebeziumDatabasesIntegrationTest.class); + + private final SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder( + TestChannelBinderConfiguration + .getCompleteConfiguration(DebeziumDatabasesIntegrationTest.TestApplication.class)) + .web(WebApplicationType.NONE) + .properties( + "spring.cloud.function.definition=debeziumSupplier", + // Flattening: + // https://debezium.io/documentation/reference/stable/transformations/event-flattening.html + "debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.drop.tombstones=false", + "debezium.properties.transforms.unwrap.delete.handling.mode=rewrite", + "debezium.properties.transforms.unwrap.add.fields=name,db,op,table", + + "debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory", + "debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore", + + "debezium.properties.schema=false", + + "debezium.properties.topic.prefix=my-topic", + "debezium.properties.name=my-connector", + "debezium.properties.database.server.id=85744", + "debezium.properties.database.server.name=my-app-connector"); + + @Test + public void mysql() { + + try (GenericContainer mySQL = new GenericContainer<>(DebeziumTestUtils.DEBEZIUM_EXAMPLE_MYSQL_IMAGE) + .withEnv("MYSQL_ROOT_PASSWORD", "debezium") + .withEnv("MYSQL_USER", "mysqluser") + .withEnv("MYSQL_PASSWORD", "mysqlpw") + .withExposedPorts(3306) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3)) { + mySQL.start(); + + try (ConfigurableApplicationContext context = applicationBuilder.run( + "--debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector", + "--debezium.properties.database.user=debezium", + "--debezium.properties.database.password=dbz", + "--debezium.properties.database.hostname=localhost", + "--debezium.properties.database.port=" + mySQL.getMappedPort(3306))) { + + OutputDestination outputDestination = context.getBean(OutputDestination.class); + + List> messages = DebeziumTestUtils.receiveAll(outputDestination); + + assertThat(messages).isNotNull(); + // Message size should correspond to the number of insert statements in: + // https://github.com/debezium/container-images/blob/main/examples/mysql/2.2/inventory.sql + assertThat(messages).hasSizeGreaterThanOrEqualTo(52); + } + mySQL.stop(); + } + } + + @Test + public void postgres() { + try (GenericContainer postgres = new GenericContainer<>(DebeziumTestUtils.DEBEZIUM_EXAMPLE_POSTGRES_IMAGE) + .withEnv("POSTGRES_USER", "postgres") + .withEnv("POSTGRES_PASSWORD", "postgres") + .withExposedPorts(5432) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3)) { + + postgres.start(); + + try (ConfigurableApplicationContext context = applicationBuilder.run( + "--debezium.properties.connector.class=io.debezium.connector.postgresql.PostgresConnector", + "--debezium.properties.database.user=postgres", + "--debezium.properties.database.password=postgres", + "--debezium.properties.slot.name=debezium", + "--debezium.properties.database.dbname=postgres", + "--debezium.properties.database.hostname=localhost", + "--debezium.properties.database.port=" + postgres.getMappedPort(5432))) { + + OutputDestination outputDestination = context.getBean(OutputDestination.class); + + List> allMessages = new ArrayList<>(); + Awaitility.await().atMost(Duration.ofMinutes(5)).until(() -> { + List> messageChunk = DebeziumTestUtils.receiveAll(outputDestination); + if (!CollectionUtils.isEmpty(messageChunk)) { + logger.info("Chunk size: " + messageChunk.size()); + allMessages.addAll(messageChunk); + } + // Message size should correspond to the number of insert statements in the sample inventor DB: + // https://github.com/debezium/container-images/blob/main/examples/postgres/2.2/inventory.sql + return allMessages.size() == 29; // Inventory DB entries + }); + } + + postgres.stop(); + } + } + + @Test + @Disabled + public void mongodb() { + GenericContainer mongodb = MongoDbContainer + .node() + .imageName(DockerImageName.parse(DebeziumTestUtils.DEBEZIUM_EXAMPLE_MONGODB_IMAGE)) + .name("mymongo") + // .port(27017) + .replicaSet("rs0") + .skipDockerDesktopLogWarning(true) + .build(); + + // GenericContainer mongodb = new GenericContainer<>(DebeziumTestUtils.DEBEZIUM_EXAMPLE_MONGODB_IMAGE) + mongodb + .withEnv("MONGODB_USER", "debezium") + .withEnv("MONGODB_PASSWORD", "dbz") + .withExposedPorts(27017) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3); + + mongodb.start(); + String id = mongodb.getContainerId(); + // String host = id.substring(0, 12); + String host = mongodb.getHost(); + String port = "" + mongodb.getMappedPort(27017); + try (ConfigurableApplicationContext context = applicationBuilder + .run("--debezium.properties.connector.class=io.debezium.connector.mongodb.MongoDbConnector", + "--debezium.properties.topic.prefix=fullfillment", + "--debezium.properties.tasks.max=1", + "--debezium.properties.mongodb.connection.string=mongodb://" + host + ":" + port + + "/?replicaSet=rs0", + // "--debezium.properties.mongodb.connection.string=mongodb://" + host + ":" + // + "27017" + // + "/?replicaSet=rs0", + "--debezium.properties.mongodb.name=dbserver1", + "--debezium.properties.mongodb.user=debezium", + "--debezium.properties.mongodb.password=dbz", + "--debezium.properties.collection.include.list=inventory[.]*")) { + + OutputDestination outputDestination = context.getBean(OutputDestination.class); + // Using local region here + List> messages = DebeziumTestUtils.receiveAll(outputDestination); + assertThat(messages).isNotNull(); + // Number of entries should match the entries inserted by: + // https://github.com/debezium/container-images/blob/main/examples/mongodb/2.2/init-inventory.sh + assertThat(messages).hasSize(666); + } + mongodb.stop(); + } + + @SpringBootConfiguration + @EnableAutoConfiguration(exclude = { MongoAutoConfiguration.class, DataSourceAutoConfiguration.class }) + @Import(DebeziumReactiveConsumerConfiguration.class) + public static class TestApplication { + } + +} diff --git a/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumDeleteHandlingIntegrationTest.java b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumDeleteHandlingIntegrationTest.java new file mode 100644 index 00000000..fab10b61 --- /dev/null +++ b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumDeleteHandlingIntegrationTest.java @@ -0,0 +1,178 @@ +/* + * Copyright 2020-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.stream.app.source.debezium.integration; + +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import org.springframework.boot.test.context.FilteredClassLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.test.context.runner.ContextConsumer; +import org.springframework.cloud.fn.supplier.debezium.DebeziumProperties; +import org.springframework.cloud.fn.supplier.debezium.DebeziumReactiveConsumerConfiguration; +import org.springframework.cloud.stream.binder.test.OutputDestination; +import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; +import org.springframework.context.ApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.kafka.support.KafkaNull; +import org.springframework.messaging.Message; +import org.springframework.test.jdbc.JdbcTestUtils; +import org.springframework.util.ClassUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Christian Tzolov + * @author David Turanski + */ +@Tag("integration") +@Testcontainers +public class DebeziumDeleteHandlingIntegrationTest { + + @Container + static GenericContainer mySqlContainer = new GenericContainer<>(DebeziumTestUtils.DEBEZIUM_EXAMPLE_MYSQL_IMAGE) + .withEnv("MYSQL_ROOT_PASSWORD", "debezium") + .withEnv("MYSQL_USER", "mysqluser") + .withEnv("MYSQL_PASSWORD", "mysqlpw") + .withExposedPorts(3306) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3); + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration( + TestChannelBinderConfiguration.getCompleteConfiguration(TestDebeziumSourceApplication.class)) + .withPropertyValues( + "spring.cloud.function.definition=debeziumSupplier", + + "debezium.properties.schema=false", + + "debezium.properties.key.converter.schemas.enable=false", + "debezium.properties.value.converter.schemas.enable=false", + + "debezium.properties.topic.prefix=my-topic", // new + + // enable flattering + "debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.add.fields=name,db", + + "debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory", // new + "debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore", + + "debezium.properties.name=my-connector", + "debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector", + "debezium.properties.database.user=debezium", + "debezium.properties.database.password=dbz", + "debezium.properties.database.hostname=localhost", + "debezium.properties.database.port=" + mySqlContainer.getMappedPort(3306), + "debezium.properties.database.server.id=85744", + "debezium.properties.database.server.name=my-app-connector", + "debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory", + + // JdbcTemplate configuration + String.format("app.datasource.url=jdbc:mysql://localhost:%d/%s?enabledTLSProtocols=TLSv1.2", + mySqlContainer.getMappedPort(3306), DebeziumTestUtils.DATABASE_NAME), + "app.datasource.username=root", + "app.datasource.password=debezium", + "app.datasource.driver-class-name=com.mysql.cj.jdbc.Driver", + "app.datasource.type=com.zaxxer.hikari.HikariDataSource"); + + @ParameterizedTest + @ValueSource(strings = { + "debezium.properties.transforms.unwrap.delete.handling.mode=none,debezium.properties.transforms.unwrap.drop.tombstones=true", + "debezium.properties.transforms.unwrap.delete.handling.mode=none,debezium.properties.transforms.unwrap.drop.tombstones=false", + "debezium.properties.transforms.unwrap.delete.handling.mode=drop,debezium.properties.transforms.unwrap.drop.tombstones=true", + "debezium.properties.transforms.unwrap.delete.handling.mode=drop,debezium.properties.transforms.unwrap.drop.tombstones=false", + "debezium.properties.transforms.unwrap.delete.handling.mode=rewrite,debezium.properties.transforms.unwrap.drop.tombstones=true", + "debezium.properties.transforms.unwrap.delete.handling.mode=rewrite,debezium.properties.transforms.unwrap.drop.tombstones=false" + }) + public void handleRecordDeletions(String properties) { + contextRunner.withPropertyValues(properties.split(",")) + .withClassLoader(new FilteredClassLoader(KafkaNull.class)) // Remove Kafka from the + .run(consumer); + + contextRunner.withPropertyValues(properties.split(",")) + .run(consumer); + } + + private String toString(Object object) { + return new String((byte[]) object); + } + + final ContextConsumer consumer = context -> { + OutputDestination outputDestination = context.getBean(OutputDestination.class); + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + DebeziumProperties props = context.getBean(DebeziumProperties.class); + + boolean isKafkaPresent = ClassUtils.isPresent( + DebeziumReactiveConsumerConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, + context.getClassLoader()); + + String deleteHandlingMode = props.getProperties().get("transforms.unwrap.delete.handling.mode"); + String isDropTombstones = props.getProperties().get("transforms.unwrap.drop.tombstones"); + + jdbcTemplate.update( + "insert into `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); + String newRecordId = jdbcTemplate.query("select * from `customers` where `first_name` = ?", + (rs, rowNum) -> rs.getString("id"), "Test666").iterator().next(); + + List> messages = DebeziumTestUtils.receiveAll(outputDestination); + assertThat(messages).hasSizeGreaterThanOrEqualTo(52); + + JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); + + Message received; + + if (deleteHandlingMode.equals("drop")) { + // Do nothing + } + else if (deleteHandlingMode.equals("none")) { + received = outputDestination.receive(Duration.ofSeconds(10).toMillis(), DebeziumTestUtils.BINDING_NAME); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo("null".getBytes()); + } + else if (deleteHandlingMode.equals("rewrite")) { + received = outputDestination.receive(Duration.ofSeconds(10).toMillis(), DebeziumTestUtils.BINDING_NAME); + assertThat(received).isNotNull(); + assertThat(toString(received.getPayload()).contains("\"__deleted\":\"true\"")); + } + + if (!(isDropTombstones.equals("true")) && isKafkaPresent) { + received = outputDestination.receive(Duration.ofSeconds(10).toMillis(), DebeziumTestUtils.BINDING_NAME); + assertThat(received).isNotNull(); + // Tombstones event should have KafkaNull payload + assertThat(received.getPayload().getClass().getCanonicalName()) + .isEqualTo(DebeziumReactiveConsumerConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL); + + Object keyRaw = received.getHeaders().get("debezium_key"); + String key = (keyRaw instanceof byte[]) ? new String((byte[]) keyRaw) : "" + keyRaw; + + // Tombstones event should carry the deleted record id in the debezium_key header + assertThat(key).isEqualTo("{\"id\":" + newRecordId + "}"); + } + + received = outputDestination.receive(Duration.ofSeconds(1).toMillis(), DebeziumTestUtils.BINDING_NAME); + assertThat(received).isNull(); + }; +} diff --git a/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumFlatteningIntegrationTest.java b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumFlatteningIntegrationTest.java new file mode 100644 index 00000000..60aa9fb7 --- /dev/null +++ b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumFlatteningIntegrationTest.java @@ -0,0 +1,301 @@ +/* + * Copyright 2020-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.stream.app.source.debezium.integration; + +import java.time.Duration; +import java.util.List; + +import net.javacrumbs.jsonunit.JsonAssert; +import net.javacrumbs.jsonunit.core.Configuration; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import org.springframework.boot.test.context.FilteredClassLoader; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.boot.test.context.runner.ContextConsumer; +import org.springframework.cloud.fn.supplier.debezium.DebeziumProperties; +import org.springframework.cloud.fn.supplier.debezium.DebeziumReactiveConsumerConfiguration; +import org.springframework.cloud.stream.binder.test.OutputDestination; +import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; +import org.springframework.context.ApplicationContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.kafka.support.KafkaNull; +import org.springframework.messaging.Message; +import org.springframework.test.jdbc.JdbcTestUtils; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Christian Tzolov + * @author David Turanski + * @author Artem Bilan + */ +@Testcontainers +@Tag("integration") +public class DebeziumFlatteningIntegrationTest { + + @Container + static GenericContainer mySqlContainer = new GenericContainer<>(DebeziumTestUtils.DEBEZIUM_EXAMPLE_MYSQL_IMAGE) + .withEnv("MYSQL_ROOT_PASSWORD", "debezium") + .withEnv("MYSQL_USER", "mysqluser") + .withEnv("MYSQL_PASSWORD", "mysqlpw") + .withExposedPorts(3306) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3); + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration( + TestChannelBinderConfiguration.getCompleteConfiguration(TestDebeziumSourceApplication.class)) + .withPropertyValues( + "spring.cloud.function.definition=debeziumSupplier", + + "debezium.properties.schema=false", + + "debezium.properties.key.converter.schemas.enable=false", + "debezium.properties.value.converter.schemas.enable=false", + + "debezium.properties.topic.prefix=my-topic", // new + + "debezium.properties.name=my-sql-connector", + + "debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory", // new + "debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore", + + "debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector", + "debezium.properties.database.user=debezium", + "debezium.properties.database.password=dbz", + "debezium.properties.database.hostname=localhost", + "debezium.properties.database.port=" + mySqlContainer.getMappedPort(3306), + "debezium.properties.database.server.id=85744", + "debezium.properties.database.server.name=my-app-connector", + "debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory", + + // JdbcTemplate configuration + String.format("app.datasource.url=jdbc:mysql://localhost:%d/%s?enabledTLSProtocols=TLSv1.2", + mySqlContainer.getMappedPort(3306), DebeziumTestUtils.DATABASE_NAME), + "app.datasource.username=root", + "app.datasource.password=debezium", + "app.datasource.driver-class-name=com.mysql.cj.jdbc.Driver", + "app.datasource.type=com.zaxxer.hikari.HikariDataSource"); + + @Test + public void noFlattenedResponseNoKafka() { + contextRunner + .withClassLoader(new FilteredClassLoader(KafkaNull.class)) // Remove Kafka from the classpath + .run(noFlatteningTest); + } + + @Test + public void noFlattenedResponseWithKafka() { + contextRunner.run(noFlatteningTest); + } + + final ContextConsumer noFlatteningTest = context -> { + OutputDestination outputDestination = context.getBean(OutputDestination.class); + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + + boolean isKafkaPresent = ClassUtils.isPresent( + DebeziumReactiveConsumerConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, + context.getClassLoader()); + + List> messages = DebeziumTestUtils.receiveAll(outputDestination); + assertThat(messages).hasSizeGreaterThanOrEqualTo(52); + + JsonAssert.assertJsonEquals(DebeziumTestUtils.resourceToString( + "classpath:/json/mysql_ddl_drop_inventory_address_table.json"), + toString(messages.get(1).getPayload()), + Configuration.empty().whenIgnoringPaths("schemaName", "tableChanges", "source.sequence", + "source.ts_ms", "ts_ms")); + assertThat(messages.get(1).getHeaders().get("debezium_destination")).isEqualTo("my-topic"); + JsonAssert.assertJsonEquals("{\"databaseName\":\"inventory\"}", + toString(messages.get(1).getHeaders().get("debezium_key"))); + + JsonAssert.assertJsonEquals( + DebeziumTestUtils.resourceToString("classpath:/json/mysql_insert_inventory_products_106.json"), + toString(messages.get(39).getPayload()), + Configuration.empty().whenIgnoringPaths("source.sequence", "source.ts_ms")); + assertThat(messages.get(39).getHeaders().get("debezium_destination")).isEqualTo("my-topic.inventory.products"); + JsonAssert.assertJsonEquals("{\"id\":106}", toString(messages.get(39).getHeaders().get("debezium_key"))); + + jdbcTemplate.update( + "insert into `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); + String newRecordId = jdbcTemplate.query("select * from `customers` where `first_name` = ?", + (rs, rowNum) -> rs.getString("id"), "Test666").iterator().next(); + jdbcTemplate.update("UPDATE `customers` SET `last_name`='Test999' WHERE first_name = 'Test666'"); + JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); + + messages = DebeziumTestUtils.receiveAll(outputDestination); + + assertThat(messages).hasSize(isKafkaPresent ? 4 : 3); + + JsonAssert.assertJsonEquals( + DebeziumTestUtils.resourceToString("classpath:/json/mysql_update_inventory_customers.json"), + toString(messages.get(1).getPayload()), Configuration.empty().whenIgnoringPaths("source.sequence")); + assertThat(messages.get(1).getHeaders().get("debezium_destination")).isEqualTo("my-topic.inventory.customers"); + JsonAssert.assertJsonEquals("{\"id\":" + newRecordId + "}", + toString(messages.get(1).getHeaders().get("debezium_key"))); + + JsonAssert.assertJsonEquals( + DebeziumTestUtils.resourceToString("classpath:/json/mysql_delete_inventory_customers.json"), + toString(messages.get(2).getPayload()), Configuration.empty().whenIgnoringPaths("source.sequence")); + assertThat(messages.get(1).getHeaders().get("debezium_destination")).isEqualTo("my-topic.inventory.customers"); + + JsonAssert.assertJsonEquals("{\"id\":" + newRecordId + "}", + toString(messages.get(1).getHeaders().get("debezium_key"))); + + if (isKafkaPresent) { + assertThat(messages.get(3).getPayload().getClass().getCanonicalName()) + .isEqualTo(DebeziumReactiveConsumerConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, + "Tombstones event should have KafkaNull payload"); + assertThat(messages.get(3).getHeaders().get("debezium_destination")) + .isEqualTo("my-topic.inventory.customers"); + JsonAssert.assertJsonEquals("{\"id\":" + newRecordId + "}", + toString(messages.get(3).getHeaders().get("debezium_key"))); + } + }; + + @Test + public void flattenedResponseNoKafka() { + contextRunner + .withPropertyValues("debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.add.fields=name,db,op", + "debezium.properties.transforms.unwrap.add.headers=name,op", + "debezium.properties.transforms.unwrap.delete.handling.mode=none", + "debezium.properties.transforms.unwrap.drop.tombstones=false") + .withClassLoader(new FilteredClassLoader(KafkaNull.class)) // Remove Kafka from the classpath + .run(flatteningTest); + } + + @Test + public void flattenedResponseWithKafka() { + contextRunner + .withPropertyValues("debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.add.fields=name,db,op", + "debezium.properties.transforms.unwrap.add.headers=name,op", + "debezium.properties.transforms.unwrap.delete.handling.mode=none", + "debezium.properties.transforms.unwrap.drop.tombstones=false") + .run(flatteningTest); + } + + @Test + public void flattenedResponseWithKafkaDropTombstone() { + contextRunner + .withPropertyValues("debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.add.fields=name,db,op", + "debezium.properties.transforms.unwrap.add.headers=name,op", + "debezium.properties.transforms.unwrap.delete.handling.mode=none", + "debezium.properties.transforms.unwrap.drop.tombstones=true") + .run(flatteningTest); + } + + final ContextConsumer flatteningTest = context -> { + OutputDestination outputDestination = context.getBean(OutputDestination.class); + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + + boolean isKafkaPresent = ClassUtils.isPresent( + DebeziumReactiveConsumerConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, + context.getClassLoader()); + + List> messages = DebeziumTestUtils.receiveAll(outputDestination); + assertThat(messages).hasSizeGreaterThanOrEqualTo(52); + + DebeziumProperties props = context.getBean(DebeziumProperties.class); + + String deleteHandlingMode = props.getProperties().get("transforms.unwrap.delete.handling.mode"); + String isDropTombstones = props.getProperties().get("transforms.unwrap.drop.tombstones"); + + JsonAssert.assertJsonEquals(DebeziumTestUtils.resourceToString( + "classpath:/json/mysql_ddl_drop_inventory_address_table.json"), + toString(messages.get(1).getPayload()), + Configuration.empty().whenIgnoringPaths("schemaName", "tableChanges", "source.sequence", + "source.ts_ms", "ts_ms")); + assertThat(messages.get(1).getHeaders().get("debezium_destination")).isEqualTo("my-topic"); + JsonAssert.assertJsonEquals("{\"databaseName\":\"inventory\"}", + toString(messages.get(1).getHeaders().get("debezium_key"))); + + if (isFlatteningEnabled(props)) { + JsonAssert.assertJsonEquals( + DebeziumTestUtils + .resourceToString("classpath:/json/mysql_flattened_insert_inventory_products_106.json"), + toString(messages.get(39).getPayload())); + } + else { + JsonAssert.assertJsonEquals( + DebeziumTestUtils.resourceToString("classpath:/json/mysql_insert_inventory_products_106.json"), + toString(messages.get(39).getPayload())); + } + assertThat(messages.get(39).getHeaders().get("debezium_destination")).isEqualTo("my-topic.inventory.products"); + JsonAssert.assertJsonEquals("{\"id\":106}", toString(messages.get(39).getHeaders().get("debezium_key"))); + + jdbcTemplate.update( + "insert into `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); + String newRecordId = jdbcTemplate.query("select * from `customers` where `first_name` = ?", + (rs, rowNum) -> rs.getString("id"), "Test666").iterator().next(); + jdbcTemplate.update("UPDATE `customers` SET `last_name`='Test999' WHERE first_name = 'Test666'"); + JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); + + messages = DebeziumTestUtils.receiveAll(outputDestination); + + assertThat(messages).hasSize((isDropTombstones.equals("false") && isKafkaPresent) ? 4 : 3); + + JsonAssert.assertJsonEquals( + DebeziumTestUtils.resourceToString("classpath:/json/mysql_flattened_update_inventory_customers.json"), + toString(messages.get(1).getPayload())); + + assertThat(messages.get(1).getHeaders().get("debezium_destination")).isEqualTo("my-topic.inventory.customers"); + JsonAssert.assertJsonEquals("{\"id\":" + newRecordId + "}", + toString(messages.get(1).getHeaders().get("debezium_key"))); + + if (deleteHandlingMode.equals("none")) { + assertThat(toString(messages.get(2).getPayload())).isEqualTo("null"); + assertThat(messages.get(1).getHeaders().get("debezium_destination")).isEqualTo("my-topic.inventory.customers"); + JsonAssert.assertJsonEquals("{\"id\":" + newRecordId + "}", + toString(messages.get(1).getHeaders().get("debezium_key"))); + } + + if (isDropTombstones.equals("false") && isKafkaPresent) { + assertThat(messages.get(3).getPayload().getClass().getCanonicalName()) + .isEqualTo(DebeziumReactiveConsumerConfiguration.ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, + "Tombstones event should have KafkaNull payload"); + assertThat(messages.get(3).getHeaders().get("debezium_destination")) + .isEqualTo("my-topic.inventory.customers"); + JsonAssert.assertJsonEquals("{\"id\":" + newRecordId + "}", + toString(messages.get(3).getHeaders().get("debezium_key"))); + } + }; + + private static boolean isFlatteningEnabled(DebeziumProperties props) { + String unwrapType = props.getProperties().get("transforms.unwrap.type"); + return StringUtils.hasText(unwrapType) && unwrapType.equals("io.debezium.transforms.ExtractNewRecordState"); + } + + private String toString(Object object) { + if (object instanceof String) { + return (String) object; + } + return new String((byte[]) object); + } + +} diff --git a/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumSupplierAvroFormatTest.java b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumSupplierAvroFormatTest.java new file mode 100644 index 00000000..f3738139 --- /dev/null +++ b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumSupplierAvroFormatTest.java @@ -0,0 +1,122 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.stream.app.source.debezium.integration; + +import java.time.Duration; +import java.util.List; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.cloud.stream.binder.test.OutputDestination; +import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.messaging.Message; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Christian Tzolov + */ +@Tag("integration") +@Testcontainers +public class DebeziumSupplierAvroFormatTest { + + // E.g. docker run -it --rm --name apicurio -p 8080:8080 apicurio/apicurio-registry-mem:2.4.1.Final + @Container + static GenericContainer apicurio = new GenericContainer<>("apicurio/apicurio-registry-mem:2.4.1.Final") + .withExposedPorts(8080) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3); + + @Container + static GenericContainer debeziumMySQL = new GenericContainer<>(DebeziumTestUtils.DEBEZIUM_EXAMPLE_MYSQL_IMAGE) + .withEnv("MYSQL_ROOT_PASSWORD", "debezium") + .withEnv("MYSQL_USER", "mysqluser") + .withEnv("MYSQL_PASSWORD", "mysqlpw") + .withExposedPorts(3306) + .withStartupTimeout(Duration.ofSeconds(120)) + .withStartupAttempts(3); + + private final SpringApplicationBuilder applicationBuilder = new SpringApplicationBuilder( + TestChannelBinderConfiguration.getCompleteConfiguration(TestDebeziumSourceApplication.class)) + .web(WebApplicationType.NONE) + .properties( + "spring.cloud.function.definition=debeziumSupplier", + + "debezium.format=AVRO", + + "debezium.properties.key.converter=io.apicurio.registry.utils.converter.AvroConverter", + "debezium.properties.key.converter.apicurio.registry.auto-register=true", + "debezium.properties.key.converter.apicurio.registry.find-latest=true", + "debezium.properties.value.converter=io.apicurio.registry.utils.converter.AvroConverter", + "debezium.properties.value.converter.apicurio.registry.auto-register=true", + "debezium.properties.value.converter.apicurio.registry.find-latest=true", + "debezium.properties.schema.name.adjustment.mode=avro", + + "debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory", + "debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore", + + "debezium.properties.topic.prefix=my-topic", + "debezium.properties.name=my-connector", + "debezium.properties.database.server.id=85744", + "debezium.properties.database.server.name=my-app-connector", + + "debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector", + "debezium.properties.database.user=debezium", + "debezium.properties.database.password=dbz", + "debezium.properties.database.hostname=localhost", + + // JdbcTemplate configuration + String.format("app.datasource.url=jdbc:mysql://localhost:%d/%s?enabledTLSProtocols=TLSv1.2", + debeziumMySQL.getMappedPort(3306), DebeziumTestUtils.DATABASE_NAME), + "app.datasource.username=root", + "app.datasource.password=debezium", + "app.datasource.driver-class-name=com.mysql.cj.jdbc.Driver", + "app.datasource.type=com.zaxxer.hikari.HikariDataSource"); + + @Test + public void mysqlWithAvroContentFormat() { + + String MYSQL_MAPPED_PORT = String.valueOf(debeziumMySQL.getMappedPort(3306)); + String APICURIO_URL = "http://localhost:" + String.valueOf(apicurio.getMappedPort(8080)) + "/apis/registry/v2"; + + try (ConfigurableApplicationContext context = applicationBuilder.run( + "--debezium.properties.key.converter.apicurio.registry.url=" + APICURIO_URL, + "--debezium.properties.value.converter.apicurio.registry.url=" + APICURIO_URL, + "--debezium.properties.database.port=" + MYSQL_MAPPED_PORT)) { + + OutputDestination outputDestination = context.getBean(OutputDestination.class); + + // Using local region here + List> messages = DebeziumTestUtils.receiveAll(outputDestination); + + assertThat(messages).isNotNull(); + // Message size should correspond to the number of insert statements in the sample inventor DB + // configured by: + // https://github.com/debezium/container-images/blob/main/examples/mysql/2.1/inventory.sql + assertThat(messages).hasSizeGreaterThanOrEqualTo(52); + // assertThat(messages).map(message -> + // message.getHeaders().get("contentType")).isEqualTo("application/avro"); // TEST utils bug. + } + } +} diff --git a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcTestUtils.java b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumTestUtils.java similarity index 64% rename from applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcTestUtils.java rename to applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumTestUtils.java index 0dd22cb9..6490e8f0 100644 --- a/applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc/CdcTestUtils.java +++ b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/DebeziumTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2020-2020 the original author or authors. + * Copyright 2020-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.cloud.stream.app.source.cdc; +package org.springframework.cloud.stream.app.source.debezium.integration; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -24,38 +24,29 @@ import java.util.List; import org.springframework.cloud.stream.binder.test.OutputDestination; import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.messaging.Message; import org.springframework.util.StreamUtils; /** * @author Christian Tzolov */ -public final class CdcTestUtils { +public final class DebeziumTestUtils { - /** - * derived from the spring.cloud.function.definition value - */ - public static final String CDC_SUPPLIER_OUT_0 = "cdcSupplier-out-0"; + public static final String DATABASE_NAME = "inventory"; + public static final String BINDING_NAME = "debeziumSupplier-out-0"; + public static final String IMAGE_TAG = "2.2.0.Final"; + public static final String DEBEZIUM_EXAMPLE_MYSQL_IMAGE = "debezium/example-mysql:" + IMAGE_TAG; + public static final String DEBEZIUM_EXAMPLE_POSTGRES_IMAGE = "debezium/example-postgres:" + IMAGE_TAG; + public static final String DEBEZIUM_EXAMPLE_MONGODB_IMAGE = "debezium/example-mongodb:" + IMAGE_TAG; - private CdcTestUtils() { - } - public static JdbcTemplate jdbcTemplate(String jdbcDriver, String jdbcUrl, String user, String password) { + private DebeziumTestUtils() { - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(jdbcDriver); - dataSource.setUrl(jdbcUrl); - dataSource.setUsername(user); - dataSource.setPassword(password); - - return new JdbcTemplate(dataSource); } public static List> receiveAll(OutputDestination outputDestination) { - return receiveAll(outputDestination, CDC_SUPPLIER_OUT_0); + return receiveAll(outputDestination, BINDING_NAME); } public static List> receiveAll(OutputDestination outputDestination, String bindingName) { @@ -66,7 +57,8 @@ public final class CdcTestUtils { if (received != null) { list.add(received); } - } while (received != null); + } + while (received != null); return list; } diff --git a/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/TestDebeziumSourceApplication.java b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/TestDebeziumSourceApplication.java new file mode 100644 index 00000000..14691b93 --- /dev/null +++ b/applications/source/debezium-source/src/test/java/org/springframework/cloud/stream/app/source/debezium/integration/TestDebeziumSourceApplication.java @@ -0,0 +1,62 @@ +/* + * Copyright 2020-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.stream.app.source.debezium.integration; + +import javax.sql.DataSource; + +import com.zaxxer.hikari.HikariDataSource; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.fn.supplier.debezium.DebeziumReactiveConsumerConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * @author Christian Tzolov + */ +@SpringBootConfiguration +@EnableAutoConfiguration(exclude = {MongoAutoConfiguration.class}) +@Import(DebeziumReactiveConsumerConfiguration.class) +public class TestDebeziumSourceApplication { + + @Bean + public JdbcTemplate myJdbcTemplate(DataSource dataSource) { + return new JdbcTemplate(dataSource); + } + + @Bean + @Primary + @ConfigurationProperties("app.datasource") + public DataSourceProperties dataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean + public HikariDataSource dataSource(DataSourceProperties dataSourceProperties) { + return dataSourceProperties.initializeDataSourceBuilder() + .type(HikariDataSource.class) + //.driverClassName("com.mysql.cj.jdbc.Driver") + .build(); + } + +} diff --git a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_ddl_drop_inventory_address_table.json b/applications/source/debezium-source/src/test/resources/json/mysql_ddl_drop_inventory_address_table.json similarity index 88% rename from applications/source/cdc-debezium-source/src/test/resources/json/mysql_ddl_drop_inventory_address_table.json rename to applications/source/debezium-source/src/test/resources/json/mysql_ddl_drop_inventory_address_table.json index bdcd6c7e..66a5d8cf 100644 --- a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_ddl_drop_inventory_address_table.json +++ b/applications/source/debezium-source/src/test/resources/json/mysql_ddl_drop_inventory_address_table.json @@ -2,8 +2,8 @@ "source": { "version": "${json-unit.ignore}", "connector": "mysql", - "name": "my-app-connector", - "ts_ms": 0, + "name": "my-topic", + "ts_ms": 1681662168850, "snapshot": "true", "db": "inventory", "table": "addresses", diff --git a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_delete_inventory_customers.json b/applications/source/debezium-source/src/test/resources/json/mysql_delete_inventory_customers.json similarity index 95% rename from applications/source/cdc-debezium-source/src/test/resources/json/mysql_delete_inventory_customers.json rename to applications/source/debezium-source/src/test/resources/json/mysql_delete_inventory_customers.json index 090b2f3c..1545ea43 100644 --- a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_delete_inventory_customers.json +++ b/applications/source/debezium-source/src/test/resources/json/mysql_delete_inventory_customers.json @@ -9,7 +9,7 @@ "source": { "version": "${json-unit.ignore}", "connector": "mysql", - "name": "my-app-connector", + "name": "my-topic", "ts_ms": "${json-unit.ignore}", "snapshot": "false", "db": "inventory", diff --git a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_flattened_insert_inventory_products_106.json b/applications/source/debezium-source/src/test/resources/json/mysql_flattened_insert_inventory_products_106.json similarity index 74% rename from applications/source/cdc-debezium-source/src/test/resources/json/mysql_flattened_insert_inventory_products_106.json rename to applications/source/debezium-source/src/test/resources/json/mysql_flattened_insert_inventory_products_106.json index abf55d0b..ef87f8f2 100644 --- a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_flattened_insert_inventory_products_106.json +++ b/applications/source/debezium-source/src/test/resources/json/mysql_flattened_insert_inventory_products_106.json @@ -1,6 +1,7 @@ { "__db" : "inventory", - "__name" : "my-app-connector", + "__name" : "my-topic", + "__op" : "r", "id": 106, "name": "hammer", "description": "16oz carpenter's hammer", diff --git a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_flattened_update_inventory_customers.json b/applications/source/debezium-source/src/test/resources/json/mysql_flattened_update_inventory_customers.json similarity index 66% rename from applications/source/cdc-debezium-source/src/test/resources/json/mysql_flattened_update_inventory_customers.json rename to applications/source/debezium-source/src/test/resources/json/mysql_flattened_update_inventory_customers.json index cbf43ac5..345ba6bc 100644 --- a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_flattened_update_inventory_customers.json +++ b/applications/source/debezium-source/src/test/resources/json/mysql_flattened_update_inventory_customers.json @@ -3,6 +3,7 @@ "first_name": "Test666", "last_name": "Test999", "email": "Test666@spring.org", - "__name": "my-app-connector", - "__db": "inventory" + "__name": "my-topic", + "__db": "inventory", + "__op": "u" } diff --git a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_insert_inventory_products_106.json b/applications/source/debezium-source/src/test/resources/json/mysql_insert_inventory_products_106.json similarity index 90% rename from applications/source/cdc-debezium-source/src/test/resources/json/mysql_insert_inventory_products_106.json rename to applications/source/debezium-source/src/test/resources/json/mysql_insert_inventory_products_106.json index 3806280c..09955a60 100644 --- a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_insert_inventory_products_106.json +++ b/applications/source/debezium-source/src/test/resources/json/mysql_insert_inventory_products_106.json @@ -9,8 +9,8 @@ "source": { "version": "${json-unit.ignore}", "connector": "mysql", - "name": "my-app-connector", - "ts_ms": 0, + "name": "my-topic", + "ts_ms": 1681663084000, "snapshot": "true", "db": "inventory", "table": "products", diff --git a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_update_inventory_customers.json b/applications/source/debezium-source/src/test/resources/json/mysql_update_inventory_customers.json similarity index 95% rename from applications/source/cdc-debezium-source/src/test/resources/json/mysql_update_inventory_customers.json rename to applications/source/debezium-source/src/test/resources/json/mysql_update_inventory_customers.json index f1a35f88..ee992d10 100644 --- a/applications/source/cdc-debezium-source/src/test/resources/json/mysql_update_inventory_customers.json +++ b/applications/source/debezium-source/src/test/resources/json/mysql_update_inventory_customers.json @@ -14,7 +14,7 @@ "source": { "version": "${json-unit.ignore}", "connector": "mysql", - "name": "my-app-connector", + "name": "my-topic", "ts_ms": "${json-unit.ignore}", "snapshot": "false", "db": "inventory", diff --git a/applications/source/cdc-debezium-source/src/test/resources/logback-test.xml b/applications/source/debezium-source/src/test/resources/logback-test.xml similarity index 100% rename from applications/source/cdc-debezium-source/src/test/resources/logback-test.xml rename to applications/source/debezium-source/src/test/resources/logback-test.xml diff --git a/applications/source/cdc-debezium-source/src/test/resources/sqlserver/Dockerfile b/applications/source/debezium-source/src/test/resources/sqlserver/Dockerfile similarity index 100% rename from applications/source/cdc-debezium-source/src/test/resources/sqlserver/Dockerfile rename to applications/source/debezium-source/src/test/resources/sqlserver/Dockerfile diff --git a/applications/source/cdc-debezium-source/src/test/resources/sqlserver/entrypoint.sh b/applications/source/debezium-source/src/test/resources/sqlserver/entrypoint.sh similarity index 100% rename from applications/source/cdc-debezium-source/src/test/resources/sqlserver/entrypoint.sh rename to applications/source/debezium-source/src/test/resources/sqlserver/entrypoint.sh diff --git a/applications/source/cdc-debezium-source/src/test/resources/sqlserver/import-data.sh b/applications/source/debezium-source/src/test/resources/sqlserver/import-data.sh similarity index 100% rename from applications/source/cdc-debezium-source/src/test/resources/sqlserver/import-data.sh rename to applications/source/debezium-source/src/test/resources/sqlserver/import-data.sh diff --git a/applications/source/cdc-debezium-source/src/test/resources/sqlserver/inventory.sql b/applications/source/debezium-source/src/test/resources/sqlserver/inventory.sql similarity index 100% rename from applications/source/cdc-debezium-source/src/test/resources/sqlserver/inventory.sql rename to applications/source/debezium-source/src/test/resources/sqlserver/inventory.sql diff --git a/applications/source/pom.xml b/applications/source/pom.xml index 4d319a5e..b1aad3cf 100644 --- a/applications/source/pom.xml +++ b/applications/source/pom.xml @@ -10,7 +10,7 @@ pom - cdc-debezium-source + debezium-source file-source ftp-source jdbc-source diff --git a/functions/common/cdc-debezium-boot-starter/README.adoc b/functions/common/cdc-debezium-boot-starter/README.adoc deleted file mode 100644 index af7320bf..00000000 --- a/functions/common/cdc-debezium-boot-starter/README.adoc +++ /dev/null @@ -1,124 +0,0 @@ -= Debezium Spring Boot Starter - -Spring Boot Starter for easy integration of https://debezium.io[Debezium] in Spring Boot applications. - -To use it you just add the `cdc-debezium-boot-starter` dependency to your application POM and implement your own `Consumer` handler to process the incoming database change events. Follow the link below for further instructions. - -https://en.wikipedia.org/wiki/Change_data_capture[Change Data Capture] (CDC) Spring Boot Starter that allows capturing change events from various databases including `MySQL`, `PostgreSQL`, `MongoDB`, `Oracle` and `SQL Server`. - -== Quick Start - -https://start.spring.io/[Start new Spring Boot project] and add the following starter dependency to activate the CDC: - -[source, xml] ----- - - org.springframework.cloud.fn - cdc-debezium-boot-starter - 1.0.0-SNAPSHOT - ----- - -NOTE: for MySQL you need to adjust the mysql client version to `mysql:mysql-connector-java:8.0.13`. - -The CDC starter setups an embedded https://debezium.io/documentation/reference/0.10/connectors/index.html[debezium connector] to capture the database changes. - -Then implement a `Consumer` bean handler to receive and process the CDC notifications: - -[source, java] ----- -@Bean -public Consumer mySourceRecordConsumer( # <1> - Function keySerializer, # <2> - Function valueSerializer) { # <3> - - return sourceRecord -> { - System.out.println(sourceRecord.topic() # <4> - + " : " + new String(keySerializer.apply(sourceRecord)) # <5> - + " : " + new String(valueSerializer.apply(sourceRecord))); # <6> - }; -} ----- - -<1> CDC event listener that is called on every data change. -<2> Optional keySerializer converter that allows to serialize the keys of the SourceRecord into a compact binary format. -<3> Optional valueSerializer converter (by default JsonConverter) that allows to serialize the SourceRecord into a compact binary format. -<4> The `topic()` provides a logical identifier of the changed data (e.g. cdc-name.DB-name.table-name) -<5> Convert kay to text message using the keySerializer -<6> Convert payload to JSON message using the valueSerializer. - -NOTE: you may have to add `@AutoConfigureBefore(CdcAutoConfiguration.class)` to your Boot class to ensure that your record consumer overrides the default handlers. - -Above handler will produce output messages like this: -[source, bash] ----- -my-app-connector.inventory.addresses : {"id":10,"customer_id":1001,"street":"3183 Moore Avenue","city":"Euless","state":"Texas","zip":"76036","type":"SHIPPING"} -my-app-connector.inventory.customers : {"id":1004,"first_name":"Anne","last_name":"Kretchmar","email":"annek@noanswer.org"} -my-app-connector.inventory.orders : {"order_number":10001,"order_date":16816,"purchaser":1001,"quantity":1,"product_id":102} -my-app-connector.inventory.products : {"id":109,"name":"spare tire","description":"24 inch spare tire","weight":22.200000762939453} -my-app-connector.inventory.products_on_hand : {"product_id":101,"quantity":3} ----- - -All Debezium connector properties are supported. Just prefix those properties with `cdc.config` prefix. - -Following snipped shows how to configure the https://debezium.io/docs/connectors/mysql/[MySqlConnector] to connect to a local MySQL database run via the `debezium/example-mysql` docker image: -[source, bash] ----- -docker run -it --rm --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=debezium -e MYSQL_USER=mysqluser -e MYSQL_PASSWORD=mysqlpw debezium/example-mysql:1.0 ----- - -[TIP] -==== -(optional) Use `mysql` client to connected to the database and to create a `debezium` user with required credentials: -[source, bash] ----- -docker run -it --rm --name mysqlterm --link mysql --rm mysql:5.7 sh -c 'exec mysql -h"$MYSQL_PORT_3306_TCP_ADDR" -P"$MYSQL_PORT_3306_TCP_PORT" -uroot -p"$MYSQL_ENV_MYSQL_ROOT_PASSWORD"' -mysql> GRANT SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'debezium' IDENTIFIED BY 'dbz'; ----- -==== - -Configure `cdc-debezium-boot-starter` for consuming cdc events from the MySQL: - -[source,properties] ----- -cdc.name=my-sql-connector # <1> - -cdc.connector=mysql # <2> - -cdc.config.database.server.id=85744 # <3> -cdc.config.database.server.name=my-app-connector # <3> -cdc.config.database.user=debezium # <3> -cdc.config.database.password=dbz # <3> -cdc.config.database.hostname=localhost # <3> -cdc.config.database.port=3306 # <3> - -cdc.schema=false # <4> - -cdc.flattening.enabled=true # <5> ----- - -<1> Metadata used to identify and dispatch the events received by this cdc consumer instance. -<2> Configures the CDC Source to use https://debezium.io/docs/connectors/mysql/[MySqlConnector]. (equivalent to setting `cdc.config.connector.class=io.debezium.connector.mysql.MySqlConnector`). -<3> Connector specific configurations. MySQL server logical name, connect location and access credentials. -<4> Do not serialize the record's schema in the output messages. -<5> Enables the https://debezium.io/docs/configuration/event-flattening/[CDC Event Flattening] feature. - -The full list of properties: - -==== Options - -//tag::configuration-properties[] -$$cdc.config$$:: $$Spring pass-trough wrapper for debezium configuration properties. All properties with a 'cdc.config.' prefix are native Debezium properties. The prefix is removed, converting them into Debezium io.debezium.config.Configuration.$$ *($$Map$$, default: `$$$$`)* -$$cdc.connector$$:: $$Shortcut for the cdc.config.connector.class property. Either of those can be used as long as they do not contradict with each other.$$ *($$ConnectorType$$, default: `$$$$`, possible values: `mysql`,`postgres`,`mongodb`,`oracle`,`sqlserver`)* -$$cdc.flattening.add-fields$$:: $$Comma separated list of metadata fields to add to the flattened message. The fields will be prefixed with "__" or "__[<]struct]__", depending on the specification of the struct.$$ *($$String$$, default: `$$$$`)* -$$cdc.flattening.add-headers$$:: $$Comma separated list specify a list of metadata fields to add to the header of the flattened message. The fields will be prefixed with "__" or "__[struct]__".$$ *($$String$$, default: `$$$$`)* -$$cdc.flattening.delete-handling-mode$$:: $$Options for handling deleted records: (1) none - pass the records through, (2) drop - remove the records and (3) rewrite - add a '__deleted' field to the records.$$ *($$DeleteHandlingMode$$, default: `$$$$`, possible values: `drop`,`rewrite`,`none`)* -$$cdc.flattening.drop-tombstones$$:: $$By default Debezium generates tombstone records to enable Kafka compaction on deleted records. The dropTombstones can suppress the tombstone records.$$ *($$Boolean$$, default: `$$true$$`)* -$$cdc.flattening.enabled$$:: $$Enable flattening the source record events (https://debezium.io/docs/configuration/event-flattening).$$ *($$Boolean$$, default: `$$true$$`)* -$$cdc.name$$:: $$Unique name for this sourceConnector instance.$$ *($$String$$, default: `$$$$`)* -$$cdc.offset.commit-timeout$$:: $$Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt.$$ *($$Duration$$, default: `$$5000ms$$`)* -$$cdc.offset.flush-interval$$:: $$Interval at which to try committing offsets. The default is 1 minute.$$ *($$Duration$$, default: `$$60000ms$$`)* -$$cdc.offset.policy$$:: $$Offset storage commit policy.$$ *($$OffsetPolicy$$, default: `$$$$`)* -$$cdc.offset.storage$$:: $$Kafka connector tracks the number processed records and regularly stores the count (as "offsets") in a preconfigured metadata storage. On restart the connector resumes the reading from the last recorded source offset.$$ *($$OffsetStorageType$$, default: `$$$$`, possible values: `memory`,`file`,`kafka`,`metadata`)* -$$cdc.schema$$:: $$Include the schema's as part of the outbound message.$$ *($$Boolean$$, default: `$$false$$`)* -//end::configuration-properties[] diff --git a/functions/common/cdc-debezium-boot-starter/pom.xml b/functions/common/cdc-debezium-boot-starter/pom.xml deleted file mode 100644 index fce6e9b0..00000000 --- a/functions/common/cdc-debezium-boot-starter/pom.xml +++ /dev/null @@ -1,104 +0,0 @@ - - - 4.0.0 - - - org.springframework.cloud.fn - spring-functions-parent - 4.0.0-SNAPSHOT - ../../spring-functions-parent/pom.xml - - - cdc-debezium-boot-starter - cdc-debezium-boot-starter - Change Data Capture (CDC) Debezium Boot Starter - - - 1.9.6.Final - - - - - - org.springframework.cloud.fn - cdc-debezium-common - ${project.version} - - - slf4j-log4j12 - org.slf4j - - - - - - io.debezium - debezium-connector-mysql - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-mongodb - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-postgres - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-oracle - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-sqlserver - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - - org.springframework - spring-jdbc - test - - - - com.zaxxer - HikariCP - test - - - - diff --git a/functions/common/cdc-debezium-boot-starter/src/main/java/org/springframework/cloud/fn/common/cdc/CdcAutoConfiguration.java b/functions/common/cdc-debezium-boot-starter/src/main/java/org/springframework/cloud/fn/common/cdc/CdcAutoConfiguration.java deleted file mode 100644 index 8c7db92f..00000000 --- a/functions/common/cdc-debezium-boot-starter/src/main/java/org/springframework/cloud/fn/common/cdc/CdcAutoConfiguration.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import java.util.function.Consumer; -import java.util.function.Function; - -import jakarta.annotation.PostConstruct; -import jakarta.annotation.PreDestroy; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.kafka.connect.source.SourceRecord; - -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; - -/** - * @author Christian Tzolov - */ -@AutoConfiguration -@Import(CdcCommonConfiguration.class) -public class CdcAutoConfiguration { - - private static final Log logger = LogFactory.getLog(CdcAutoConfiguration.class); - - @Bean - @ConditionalOnMissingBean - public Consumer defaultSourceRecordConsumer() { - return sourceRecord -> logger.info("[CDC Event]: " + ((sourceRecord == null) ? "null" : sourceRecord.toString())); - } - - @Bean - public EmbeddedEngineExecutorService embeddedEngine(EmbeddedEngine.Builder embeddedEngineBuilder, - Consumer sourceRecordConsumer, Function recordFlattening) { - - EmbeddedEngine embeddedEngine = embeddedEngineBuilder - .notifying(sourceRecord -> sourceRecordConsumer.accept(recordFlattening.apply(sourceRecord))) - .build(); - - return new EmbeddedEngineExecutorService(embeddedEngine) { - @PostConstruct - @Override - public void start() { - super.start(); - } - - @PreDestroy - @Override - public void close() { - super.close(); - } - }; - } -} diff --git a/functions/common/cdc-debezium-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/functions/common/cdc-debezium-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports deleted file mode 100644 index 5cafc4ed..00000000 --- a/functions/common/cdc-debezium-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ /dev/null @@ -1 +0,0 @@ -org.springframework.cloud.fn.common.cdc.CdcAutoConfiguration diff --git a/functions/common/cdc-debezium-boot-starter/src/test/java/org/springframework/cloud/fn/common/cdc/CdcBootStarterIntegrationTest.java b/functions/common/cdc-debezium-boot-starter/src/test/java/org/springframework/cloud/fn/common/cdc/CdcBootStarterIntegrationTest.java deleted file mode 100644 index ad6e5ba8..00000000 --- a/functions/common/cdc-debezium-boot-starter/src/test/java/org/springframework/cloud/fn/common/cdc/CdcBootStarterIntegrationTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2020-2021 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import java.time.Duration; - -import com.zaxxer.hikari.HikariDataSource; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.utility.DockerImageName; - -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.test.jdbc.JdbcTestUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - -/** - * @author Christian Tzolov - * @author David Turanski - * @author Artem Bilan - */ - -@Tag("integration") -@Testcontainers -public class CdcBootStarterIntegrationTest { - - private static final String DATABASE_NAME = "inventory"; - - private static String MAPPED_PORT; - - @Container - static GenericContainer debeziumMySQL = - new GenericContainer<>(DockerImageName.parse("debezium/example-mysql:1.9.6.Final")) - .withEnv("MYSQL_ROOT_PASSWORD", "debezium") - .withEnv("MYSQL_USER", "mysqluser") - .withEnv("MYSQL_PASSWORD", "mysqlpw") - // .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("mysql"))) - .withExposedPorts(3306) - .withStartupTimeout(Duration.ofSeconds(120)) - .withStartupAttempts(3); - - private static JdbcTemplate jdbcTemplate; - - @BeforeAll - static void setup() { - MAPPED_PORT = String.valueOf(debeziumMySQL.getMappedPort(3306)); - jdbcTemplate = jdbcTemplate( - "com.mysql.cj.jdbc.Driver", - "jdbc:mysql://localhost:" + MAPPED_PORT + "/" + DATABASE_NAME + "?enabledTLSProtocols=TLSv1.2", - "root", - "debezium"); - } - - private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withUserConfiguration(TestCdcApplication.class) - .withPropertyValues( - "spring.datasource.type=com.zaxxer.hikari.HikariDataSource", - "cdc.name=my-sql-connector", - "cdc.schema=false", - "cdc.flattening.enabled=true", - "cdc.stream.header.offset=true", - "cdc.connector=mysql", - "cdc.config.database.user=debezium", - "cdc.config.database.password=dbz", - "cdc.config.database.hostname=localhost", - "cdc.config.database.port=" + MAPPED_PORT, - "cdc.config.database.server.id=85744", - "cdc.config.database.server.name=my-app-connector", - "cdc.config.database.history=io.debezium.relational.history.MemoryDatabaseHistory"); - - @Test - public void consumerTest() { - contextRunner - .withPropertyValues( - "cdc.flattening.deleteHandlingMode=drop", - "cdc.flattening.dropTombstones=true") - .run(context -> { - TestCdcApplication.TestSourceRecordConsumer testConsumer = context - .getBean(TestCdcApplication.TestSourceRecordConsumer.class); - jdbcTemplate.update( - "insert into `customers`(`first_name`,`last_name`,`email`) " + - "VALUES('Test666', 'Test666', 'Test666@spring.org')"); - JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); - - await().atMost(Duration.ofSeconds(30)) - .untilAsserted(() -> assertThat(testConsumer.recordList).hasSizeGreaterThanOrEqualTo(52)); - }); - } - - public static JdbcTemplate jdbcTemplate(String jdbcDriver, String jdbcUrl, String user, String password) { - HikariDataSource dataSource = new HikariDataSource(); - dataSource.setDriverClassName(jdbcDriver); - dataSource.setJdbcUrl(jdbcUrl); - dataSource.setUsername(user); - dataSource.setPassword(password); - return new JdbcTemplate(dataSource); - } - -} diff --git a/functions/common/cdc-debezium-boot-starter/src/test/java/org/springframework/cloud/fn/common/cdc/TestCdcApplication.java b/functions/common/cdc-debezium-boot-starter/src/test/java/org/springframework/cloud/fn/common/cdc/TestCdcApplication.java deleted file mode 100644 index 79c79a71..00000000 --- a/functions/common/cdc-debezium-boot-starter/src/test/java/org/springframework/cloud/fn/common/cdc/TestCdcApplication.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.function.Consumer; -import java.util.function.Function; - -import org.apache.kafka.connect.source.SourceRecord; - -import org.springframework.boot.SpringBootConfiguration; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.integration.metadata.SimpleMetadataStore; - -/** - * @author Christian Tzolov - */ -@SpringBootConfiguration -@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) -public class TestCdcApplication { - - @Bean - public Consumer mySourceRecordConsumer(Function valueSerializer, - Function keySerializer) { - return new TestSourceRecordConsumer(valueSerializer, keySerializer); - } - - @Bean - public SimpleMetadataStore simpleMetadataStore() { - return new SimpleMetadataStore(); - } - - public static class TestSourceRecordConsumer implements Consumer { - - private final Function valueSerializer; - - private final Function keySerializer; - - public Map keyValue = new HashMap<>(); - - public List recordList = new CopyOnWriteArrayList<>(); - - public TestSourceRecordConsumer(Function valueSerializer, - Function keySerializer) { - this.valueSerializer = valueSerializer; - this.keySerializer = keySerializer; - } - - @Override - public void accept(SourceRecord sourceRecord) { - if (sourceRecord != null) { // ignore null records - recordList.add(sourceRecord); - Object payload = valueSerializer.apply(sourceRecord); - Object key = keySerializer.apply(sourceRecord); - keyValue.put(key, payload); - - System.out.println("[CDC Event]: " + sourceRecord.toString()); - } - } - } -} diff --git a/functions/common/cdc-debezium-common/pom.xml b/functions/common/cdc-debezium-common/pom.xml deleted file mode 100644 index fc447e8f..00000000 --- a/functions/common/cdc-debezium-common/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - 4.0.0 - - - org.springframework.cloud.fn - spring-functions-parent - 4.0.0-SNAPSHOT - ../../spring-functions-parent/pom.xml - - - cdc-debezium-common - cdc-debezium-common - Change Data Capture (CDC) Debezium Common - - - 1.9.6.Final - - - - - io.debezium - debezium-api - ${version.debezium} - - - io.debezium - debezium-embedded - ${version.debezium} - - - slf4j-log4j12 - org.slf4j - - - - - io.debezium - debezium-connector-mysql - true - ${version.debezium} - - - io.debezium - debezium-connector-postgres - true - ${version.debezium} - - - io.debezium - debezium-connector-mongodb - true - ${version.debezium} - - - io.debezium - debezium-connector-oracle - true - ${version.debezium} - - - io.debezium - debezium-connector-sqlserver - true - ${version.debezium} - - - - org.springframework.cloud.fn - metadata-store-common - ${project.version} - - - - org.springframework.integration - spring-integration-ip - - - - - diff --git a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonConfiguration.java b/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonConfiguration.java deleted file mode 100644 index 0f4efc4c..00000000 --- a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonConfiguration.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import java.util.Collections; -import java.util.Map; -import java.util.function.Function; - -import io.debezium.transforms.ExtractNewRecordState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.kafka.connect.json.JsonConverter; -import org.apache.kafka.connect.source.SourceRecord; -import org.apache.kafka.connect.storage.Converter; -import org.apache.kafka.connect.storage.OffsetBackingStore; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.util.StringUtils; - -/** - * @author Christian Tzolov - */ -@Configuration -@EnableConfigurationProperties(CdcCommonProperties.class) -@Import(CdcOffsetBackingStoreConfiguration.class) -public class CdcCommonConfiguration { - - private static final Log logger = LogFactory.getLog(CdcCommonConfiguration.class); - - @Bean - public io.debezium.config.Configuration configuration(CdcCommonProperties properties) { - Map configMap = properties.getConfig(); - return io.debezium.config.Configuration.from(configMap); - } - - @Bean - public Function recordFlattening(CdcCommonProperties properties, - ExtractNewRecordState extractNewRecordState) { - return sourceRecord -> properties.getFlattening().isEnabled() ? - (SourceRecord) extractNewRecordState.apply(sourceRecord) : sourceRecord; - } - - @Bean - public ExtractNewRecordState extractNewRecordState(CdcCommonProperties properties) { - ExtractNewRecordState extractNewRecordState = new ExtractNewRecordState(); - Map config = extractNewRecordState.config().defaultValues(); - config.put("drop.tombstones", properties.getFlattening().isDropTombstones()); - config.put("delete.handling.mode", properties.getFlattening().getDeleteHandlingMode().name()); - if (!StringUtils.isEmpty(properties.getFlattening().getAddHeaders())) { - config.put("add.headers", properties.getFlattening().getAddHeaders()); - } - if (!StringUtils.isEmpty(properties.getFlattening().getAddFields())) { - config.put("add.fields", properties.getFlattening().getAddFields()); - } - - extractNewRecordState.configure(config); - return extractNewRecordState; - } - - @Bean - @ConditionalOnMissingBean - public JsonConverter jsonConverter(CdcCommonProperties properties) { - JsonConverter jsonConverter = new JsonConverter(); - jsonConverter.configure(Collections.singletonMap("schemas.enable", properties.isSchema()), false); - return jsonConverter; - } - - @Bean - public Function valueSerializer(Converter valueConverter) { - return sourceRecord -> valueConverter.fromConnectData( - sourceRecord.topic(), sourceRecord.valueSchema(), sourceRecord.value()); - } - - @Bean - public Function keySerializer(Converter valueConverter) { - return sourceRecord -> valueConverter.fromConnectData( - sourceRecord.topic(), sourceRecord.keySchema(), sourceRecord.key()); - } - - @Bean - public EmbeddedEngine.Builder embeddedEngineBuilder(CdcCommonProperties properties, - OffsetBackingStore offsetBackingStore) { - - if (!properties.getConfig().containsKey("connector.class")) { - properties.getConfig().put("connector.class", properties.getConnector().connectorClass); - } - - if (!properties.getConfig().containsKey("name")) { - properties.getConfig().put("name", properties.getName()); - } - - if (!properties.getConfig().containsKey("offset.flush.interval.ms")) { - properties.getConfig().put("offset.flush.interval.ms", properties.getOffset().getFlushInterval().toMillis() + ""); - } - - if (!properties.getConfig().containsKey("offset.flush.timeout.ms")) { - properties.getConfig().put("offset.flush.timeout.ms", properties.getOffset().getCommitTimeout().toMillis() + ""); - } - - if (!properties.getConfig().containsKey("offset.commit.policy")) { - properties.getConfig().put("offset.commit.policy", properties.getOffset().getPolicy().policyClass); - } - - if (!properties.getConfig().containsKey("offset.storage")) { - properties.getConfig().put("offset.storage", properties.getOffset().getStorage().offsetStorageClass); - } - - return EmbeddedEngine.create() - .using(io.debezium.config.Configuration.from(properties.getConfig())) - .offsetBackingStore(offsetBackingStore); - } - -} diff --git a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonProperties.java b/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonProperties.java deleted file mode 100644 index 4cba3891..00000000 --- a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonProperties.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; - -import jakarta.validation.constraints.AssertTrue; -import jakarta.validation.constraints.NotEmpty; -import jakarta.validation.constraints.NotNull; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; - -/** - * - * @author Christian Tzolov - */ -@ConfigurationProperties("cdc") -@Validated -public class CdcCommonProperties { - - /** - * Unique name for this sourceConnector instance. - */ - @NotEmpty - private String name; - - /** - * Shortcut for the cdc.config.connector.class property. Either of those can be used as long as they do not - * contradict with each other. - */ - @NotNull - private ConnectorType connector = null; - - private final Offset offset = new Offset(); - - /** - * Include the schema's as part of the outbound message. - */ - private boolean schema = false; - - /** - * Event Flattening (https://debezium.io/docs/configuration/event-flattening). - */ - private final Flattening flattening = new Flattening(); - - /** - * Spring pass-trough wrapper for debezium configuration properties. - * All properties with a 'cdc.config.' prefix are native Debezium properties. - * The prefix is removed, converting them into Debezium io.debezium.config.Configuration. - */ - private Map config = defaultConfig(); - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Offset getOffset() { - return offset; - } - - public Flattening getFlattening() { - return flattening; - } - - public Map getConfig() { - return config; - } - - public boolean isSchema() { - return schema; - } - - public void setSchema(boolean schema) { - this.schema = schema; - } - - private Map defaultConfig() { - Map defaultConfig = new HashMap<>(); - defaultConfig.put("database.history", "io.debezium.relational.history.MemoryDatabaseHistory"); - //defaultConfig.put("offset.flush.interval.ms", "60000"); - return defaultConfig; - } - - public ConnectorType getConnector() { - return connector; - } - - public void setConnector(ConnectorType connector) { - this.connector = connector; - } - - @AssertTrue - public boolean connectorIsSet() { - return this.getConnector() != null || this.getConfig().containsKey("connector.class"); - } - - public static class Offset { - - /** - * Interval at which to try committing offsets. The default is 1 minute. - */ - private Duration flushInterval = Duration.ofMillis(60000); - - /** - * Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to - * offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. - */ - private Duration commitTimeout = Duration.ofMillis(5000); - - /** - * Offset storage commit policy. - */ - private OffsetPolicy policy = OffsetPolicy.periodic; - - /** - * Kafka connector tracks the number processed records and regularly stores the count (as "offsets") in a - * preconfigured metadata storage. On restart the connector resumes the reading from the last recorded source offset. - */ - private OffsetStorageType storage = OffsetStorageType.metadata; - - public enum OffsetPolicy { - /** periodic. */ - periodic("io.debezium.embedded.spi.OffsetCommitPolicy$PeriodicCommitOffsetPolicy"), - /** always. */ - always("OffsetCommitPolicy.AlwaysCommitOffsetPolicy.class.getName()"); - - /** policy. */ - public final String policyClass; - - OffsetPolicy(String policyClassName) { - this.policyClass = policyClassName; - } - } - - public Duration getFlushInterval() { - return flushInterval; - } - - public void setFlushInterval(Duration flushInterval) { - this.flushInterval = flushInterval; - } - - public Duration getCommitTimeout() { - return commitTimeout; - } - - public void setCommitTimeout(Duration commitTimeout) { - this.commitTimeout = commitTimeout; - } - - public OffsetPolicy getPolicy() { - return policy; - } - - public void setPolicy(OffsetPolicy policy) { - this.policy = policy; - } - - public OffsetStorageType getStorage() { - return storage; - } - - public void setStorage(OffsetStorageType storage) { - this.storage = storage; - } - - } - - public enum OffsetStorageType { - /** memory offset storage type. */ - memory("org.apache.kafka.connect.storage.MemoryOffsetBackingStore"), - /** File offset storage type. */ - file("org.apache.kafka.connect.storage.FileOffsetBackingStore"), - /** Kafka offset storage type. */ - kafka("org.apache.kafka.connect.storage.KafkaOffsetBackingStore"), - /** Metadata offset storage type. */ - metadata("org.springframework.cloud.stream.app.cdc.common.core.store.MetadataStoreOffsetBackingStore"); - - /** Class name of the Offset Storage. */ - public final String offsetStorageClass; - - OffsetStorageType(String type) { - this.offsetStorageClass = type; - } - } - - public enum ConnectorType { - /** MySql connector type. */ - mysql("io.debezium.connector.mysql.MySqlConnector"), - /** Postgres connector type. */ - postgres("io.debezium.connector.postgresql.PostgresConnector"), - /** Mongodb connector type. */ - mongodb("io.debezium.connector.mongodb.MongoDbConnector"), - /** Oracle connector type. */ - oracle("io.debezium.connector.oracle.OracleConnector"), - /** SqlServer connector type. */ - sqlserver("io.debezium.connector.sqlserver.SqlServerConnector"); - - /** Connector class name. */ - public final String connectorClass; - - ConnectorType(String type) { - this.connectorClass = type; - } - } - - public enum DeleteHandlingMode { - /** records are removed. */ - drop, - /** add a __deleted column with true/false values based on record operation. */ - rewrite, - /** pass delete events. */ - none - } - - /** - * https://debezium.io/documentation/reference/0.10/configuration/event-flattening.html . - * https://debezium.io/documentation/reference/0.10/configuration/event-flattening.html#configuration_options - */ - public static class Flattening { - - /** - * Enable flattening the source record events (https://debezium.io/docs/configuration/event-flattening). - */ - private boolean enabled = true; - - /** - * By default Debezium generates tombstone records to enable Kafka compaction on deleted records. - * The dropTombstones can suppress the tombstone records. - */ - private boolean dropTombstones = true; - - /** - * Options for handling deleted records: (1) none - pass the records through, (2) drop - remove the records and - * (3) rewrite - add a '__deleted' field to the records. - */ - private DeleteHandlingMode deleteHandlingMode = DeleteHandlingMode.drop; - - /** - * Comma separated list of metadata fields to add to the flattened message. - * The fields will be prefixed with "__" or "__[<]struct]__", depending on the specification of the struct. - */ - private String addFields = null; - - /** - * Comma separated list specify a list of metadata fields to add to the header of the flattened message. - * The fields will be prefixed with "__" or "__[struct]__". - */ - private String addHeaders = null; - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - public boolean isDropTombstones() { - return dropTombstones; - } - - public void setDropTombstones(boolean dropTombstones) { - this.dropTombstones = dropTombstones; - } - - public DeleteHandlingMode getDeleteHandlingMode() { - return deleteHandlingMode; - } - - public void setDeleteHandlingMode(DeleteHandlingMode deleteHandlingMode) { - this.deleteHandlingMode = deleteHandlingMode; - } - - public String getAddFields() { - return addFields; - } - - public void setAddFields(String addFields) { - this.addFields = addFields; - } - - public String getAddHeaders() { - return addHeaders; - } - - public void setAddHeaders(String addHeaders) { - this.addHeaders = addHeaders; - } - } -} diff --git a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcOffsetBackingStoreConfiguration.java b/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcOffsetBackingStoreConfiguration.java deleted file mode 100644 index ce677211..00000000 --- a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcOffsetBackingStoreConfiguration.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import org.apache.kafka.connect.storage.FileOffsetBackingStore; -import org.apache.kafka.connect.storage.KafkaOffsetBackingStore; -import org.apache.kafka.connect.storage.MemoryOffsetBackingStore; -import org.apache.kafka.connect.storage.OffsetBackingStore; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.cloud.fn.common.cdc.store.MetadataStoreOffsetBackingStore; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.integration.metadata.MetadataStore; - -/** - * @author Christian Tzolov - */ -@Configuration -public class CdcOffsetBackingStoreConfiguration { - - @Bean - @ConditionalOnMissingBean - @ConditionalOnExpression("'${cdc.config.offset.storage}'.equalsIgnoreCase('org.springframework.cloud.stream.app.cdc.common.core.store.MetadataStoreOffsetBackingStore') " + - "or '${cdc.offset.storage:metadata}'.equals('metadata')") - public OffsetBackingStore metadataStoreOffsetBackingStore(MetadataStore metadataStore) { - return new MetadataStoreOffsetBackingStore(metadataStore); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnExpression("'${cdc.config.offset.storage}'.equalsIgnoreCase('org.apache.kafka.connect.storage.FileOffsetBackingStore') " + - "or '${cdc.offset.storage:metadata}'.equalsIgnoreCase('file')") - public OffsetBackingStore fileOffsetBackingStore() { - return new FileOffsetBackingStore(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnExpression("'${cdc.config.offset.storage}'.equalsIgnoreCase('org.apache.kafka.connect.storage.KafkaOffsetBackingStore') " + - "or '${cdc.offset.storage:metadata}'.equalsIgnoreCase('kafka')") - public OffsetBackingStore kafkaOffsetBackingStore() { - return new KafkaOffsetBackingStore(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnExpression("'${cdc.config.offset.storage}'.equalsIgnoreCase('org.apache.kafka.connect.storage.MemoryOffsetBackingStore') " + - "or '${cdc.offset.storage:metadata}'.equalsIgnoreCase('memory')") - public OffsetBackingStore memoryOffsetBackingStore() { - return new MemoryOffsetBackingStore(); - } -} diff --git a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/EmbeddedEngine.java b/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/EmbeddedEngine.java deleted file mode 100644 index 3b896f66..00000000 --- a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/EmbeddedEngine.java +++ /dev/null @@ -1,1128 +0,0 @@ -/* - * Copyright Debezium Authors. - * - * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 - */ - -package org.springframework.cloud.fn.common.cdc; - -import java.io.IOException; -import java.time.Duration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executor; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -import io.debezium.annotation.ThreadSafe; -import io.debezium.config.Configuration; -import io.debezium.config.Field; -import io.debezium.config.Instantiator; -import io.debezium.embedded.StopConnectorException; -import io.debezium.embedded.Transformations; -import io.debezium.engine.DebeziumEngine; -import io.debezium.engine.StopEngineException; -import io.debezium.engine.spi.OffsetCommitPolicy; -import io.debezium.pipeline.ChangeEventSourceCoordinator; -import io.debezium.util.Clock; -import io.debezium.util.VariableLatch; -import org.apache.kafka.common.config.ConfigDef; -import org.apache.kafka.common.config.ConfigDef.Importance; -import org.apache.kafka.common.config.ConfigDef.Type; -import org.apache.kafka.common.config.ConfigDef.Width; -import org.apache.kafka.connect.connector.ConnectorContext; -import org.apache.kafka.connect.connector.Task; -import org.apache.kafka.connect.errors.RetriableException; -import org.apache.kafka.connect.json.JsonConverter; -import org.apache.kafka.connect.runtime.WorkerConfig; -import org.apache.kafka.connect.runtime.distributed.DistributedConfig; -import org.apache.kafka.connect.runtime.standalone.StandaloneConfig; -import org.apache.kafka.connect.source.SourceConnector; -import org.apache.kafka.connect.source.SourceRecord; -import org.apache.kafka.connect.source.SourceTask; -import org.apache.kafka.connect.source.SourceTaskContext; -import org.apache.kafka.connect.storage.Converter; -import org.apache.kafka.connect.storage.FileOffsetBackingStore; -import org.apache.kafka.connect.storage.KafkaOffsetBackingStore; -import org.apache.kafka.connect.storage.OffsetBackingStore; -import org.apache.kafka.connect.storage.OffsetStorageReader; -import org.apache.kafka.connect.storage.OffsetStorageReaderImpl; -import org.apache.kafka.connect.storage.OffsetStorageWriter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A mechanism for running a single Kafka Connect {@link SourceConnector} within an application's process. An embedded - * connector is entirely standalone and only talks with the source system; no Kafka, Kafka Connect, or Zookeeper - * processes are needed. Applications using an embedded connector simply set one up and supply a {@link Consumer - * consumer function} to which the connector will pass all {@link SourceRecord}s containing database change events. - *

- * With an embedded connector, the application that runs the connector assumes all responsibility for fault tolerance, - * scalability, and durability. Additionally, applications must specify how the connector can store its relational - * database schema history and offsets. By default, this information will be stored in memory and will thus be lost upon - * application restart. - *

- * Embedded connectors are designed to be submitted to an {@link Executor} or {@link ExecutorService} for execution by a - * single thread, and a running connector can be stopped either by calling {@link #stop()} from another thread or by - * interrupting the running thread (e.g., as is the case with {@link ExecutorService#shutdownNow()}). - * - * @author Randall Hauch - */ -@ThreadSafe -public final class EmbeddedEngine implements DebeziumEngine { - - /** - * A required field for an embedded connector that specifies the unique name for the connector instance. - */ - public static final Field ENGINE_NAME = Field.create("name") - .withDescription("Unique name for this connector instance.") - .required(); - - /** - * A required field for an embedded connector that specifies the name of the normal Debezium connector's Java class. - */ - public static final Field CONNECTOR_CLASS = Field.create("connector.class") - .withDescription("The Java class for the connector") - .required(); - - /** - * An optional field that specifies the name of the class that implements the {@link OffsetBackingStore} interface, - * and that will be used to store offsets recorded by the connector. - */ - public static final Field OFFSET_STORAGE = Field.create("offset.storage") - .withDescription("The Java class that implements the `OffsetBackingStore` " - + "interface, used to periodically store offsets so that, upon " - + "restart, the connector can resume where it last left off.") - .withDefault(FileOffsetBackingStore.class.getName()); - - /** - * An optional field that specifies the file location for the {@link FileOffsetBackingStore}. - * - * @see #OFFSET_STORAGE - */ - public static final Field OFFSET_STORAGE_FILE_FILENAME = Field.create(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG) - .withDescription("The file where offsets are to be stored. Required when " - + "'offset.storage' is set to the " + - FileOffsetBackingStore.class.getName() + " class.") - .withDefault(""); - - /** - * An optional field that specifies the topic name for the {@link KafkaOffsetBackingStore}. - * - * @see #OFFSET_STORAGE - */ - public static final Field OFFSET_STORAGE_KAFKA_TOPIC = Field.create(DistributedConfig.OFFSET_STORAGE_TOPIC_CONFIG) - .withDescription("The name of the Kafka topic where offsets are to be stored. " - + "Required with other properties when 'offset.storage' is set to the " - + KafkaOffsetBackingStore.class.getName() + " class.") - .withDefault(""); - - /** - * An optional field that specifies the number of partitions for the {@link KafkaOffsetBackingStore}. - * - * @see #OFFSET_STORAGE - */ - public static final Field OFFSET_STORAGE_KAFKA_PARTITIONS = Field.create(DistributedConfig.OFFSET_STORAGE_PARTITIONS_CONFIG) - .withType(ConfigDef.Type.INT) - .withDescription("The number of partitions used when creating the offset storage topic. " - + "Required with other properties when 'offset.storage' is set to the " - + KafkaOffsetBackingStore.class.getName() + " class."); - - /** - * An optional field that specifies the replication factor for the {@link KafkaOffsetBackingStore}. - * - * @see #OFFSET_STORAGE - */ - public static final Field OFFSET_STORAGE_KAFKA_REPLICATION_FACTOR = Field.create(DistributedConfig.OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG) - .withType(ConfigDef.Type.SHORT) - .withDescription("Replication factor used when creating the offset storage topic. " - + "Required with other properties when 'offset.storage' is set to the " - + KafkaOffsetBackingStore.class.getName() + " class."); - - /** - * An optional advanced field that specifies the maximum amount of time that the embedded connector should wait for - * an offset commit to complete. - */ - public static final Field OFFSET_FLUSH_INTERVAL_MS = Field.create("offset.flush.interval.ms") - .withDescription("Interval at which to try committing offsets, given in milliseconds. Defaults to 1 minute (60,000 ms).") - .withDefault(60000L) - .withValidation(Field::isNonNegativeInteger); - - /** - * An optional advanced field that specifies the maximum amount of time that the embedded connector should wait for - * an offset commit to complete. - */ - public static final Field OFFSET_COMMIT_TIMEOUT_MS = Field.create("offset.flush.timeout.ms") - .withDescription("Time to wait for records to flush and partition offset data to be" - + " committed to offset storage before cancelling the process and restoring the offset " - + "data to be committed in a future attempt, given in milliseconds. Defaults to 5 seconds (5000 ms).") - .withDefault(5000L) - .withValidation(Field::isPositiveInteger); - - public static final Field OFFSET_COMMIT_POLICY = Field.create("offset.commit.policy") - .withDescription("The fully-qualified class name of the commit policy type. This class must implement the interface " - + OffsetCommitPolicy.class.getName() - + ". The default is a periodic commit policy based upon time intervals.") - .withDefault(io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy.class.getName()) - .withValidation(Field::isClassName); - - protected static final Field INTERNAL_KEY_CONVERTER_CLASS = Field.create("internal.key.converter") - .withDescription("The Converter class that should be used to serialize and deserialize key data for offsets.") - .withDefault(JsonConverter.class.getName()); - - protected static final Field INTERNAL_VALUE_CONVERTER_CLASS = Field.create("internal.value.converter") - .withDescription("The Converter class that should be used to serialize and deserialize value data for offsets.") - .withDefault(JsonConverter.class.getName()); - - /** - * A list of SMTs to be applied on the messages generated by the engine. - */ - public static final Field TRANSFORMS = Field.create("transforms") - .withDisplayName("List of prefixes defining transformations.") - .withType(Type.STRING) - .withWidth(Width.MEDIUM) - .withImportance(Importance.LOW) - .withDescription("Optional list of single message transformations applied on the messages. " - + "The transforms are defined using '.type' config option and configured using options '.

- * This method returns immediately if the connector has completed already. - * - * @throws InterruptedException if the current thread is interrupted while waiting - */ - public void await() throws InterruptedException { - this.completed.await(); - } - - /** - * Causes the current thread to wait until the {@link #handle(boolean, String, Throwable) completion occurs}, - * unless the thread is {@linkplain Thread#interrupt interrupted}, or the specified waiting time elapses. - *

- * This method returns immediately if the connector has completed already. - * - * @param timeout the maximum time to wait - * @param unit the time unit of the {@code timeout} argument - * @return {@code true} if the completion was received, or {@code false} if the waiting time elapsed before the - * completion was received. - * @throws InterruptedException if the current thread is interrupted while waiting - */ - public boolean await(long timeout, TimeUnit unit) throws InterruptedException { - return this.completed.await(timeout, unit); - } - - /** - * Determine if the connector has completed. - * - * @return {@code true} if the connector has completed, or {@code false} if the connector is still running and - * this callback has not yet been {@link #handle(boolean, String, Throwable) notified} - */ - public boolean hasCompleted() { - return completed.getCount() == 0; - } - - /** - * Get whether the connector completed normally. - * - * @return {@code true} if the connector completed normally, or {@code false} if the connector produced an error - * that prevented startup or premature termination (or the connector has not yet {@link #hasCompleted() - * completed}) - */ - public boolean success() { - return success; - } - - /** - * Get the completion message. - * - * @return the completion message, or null if the connector has not yet {@link #hasCompleted() completed} - */ - public String message() { - return message; - } - - /** - * Get the completion error, if there is one. - * - * @return the completion error, or null if there is no error or connector has not yet {@link #hasCompleted() - * completed} - */ - public Throwable error() { - return error; - } - - /** - * Determine if there is a completion error. - * - * @return {@code true} if there is a {@link #error completion error}, or {@code false} if there is no error or - * the connector has not yet {@link #hasCompleted() completed} - */ - public boolean hasError() { - return error != null; - } - } - - /** - * Contract passed to {@link ChangeConsumer}s, allowing them to commit single records as they have been processed - * and to signal that offsets may be flushed eventually. - */ - @ThreadSafe - @Deprecated - public static interface RecordCommitter extends DebeziumEngine.RecordCommitter { - } - - /** - * A contract invoked by the embedded engine when it has received a batch of change records to be processed. Allows - * to process multiple records in one go, acknowledging their processing once that's done. - */ - @Deprecated - public static interface ChangeConsumer extends DebeziumEngine.ChangeConsumer { - } - - private static ChangeConsumer buildDefaultChangeConsumer(Consumer consumer) { - return new ChangeConsumer() { - - /** - * the default implementation that is compatible with the old Consumer api. - * - * On every record, it calls the consumer, and then only marks the record as processed when accept returns, - * additionally, it handles StopConnectorExceptions and ensures that we all ways try and mark a batch as - * finished, even with exceptions - * @param records the records to be processed - * @param committer the committer that indicates to the system that we are finished - * - * @throws Exception - */ - @Override - public void handleBatch(List records, DebeziumEngine.RecordCommitter committer) throws InterruptedException { - for (SourceRecord record : records) { - try { - consumer.accept(record); - committer.markProcessed(record); - } - catch (StopConnectorException | StopEngineException ex) { - // ensure that we mark the record as finished - // in this case - committer.markProcessed(record); - throw ex; - } - } - committer.markBatchFinished(); - } - }; - } - - /** - * A builder to set up and create {@link EmbeddedEngine} instances. - */ - @Deprecated - public static interface Builder extends DebeziumEngine.Builder { - - /** - * Use the specified configuration for the connector. The configuration is assumed to already be valid. - * - * @param config the configuration - * @return this builder object so methods can be chained together; never null - */ - Builder using(Configuration config); - - /** - * Use the specified clock when needing to determine the current time. Passing null or not calling - * this method results in the connector using the {@link Clock#system() system clock}. - * - * @param clock the clock - * @return this builder object so methods can be chained together; never null - */ - Builder using(Clock clock); - - // backward compatibility methods - @Override - Builder notifying(Consumer consumer); - - @Override - Builder notifying(DebeziumEngine.ChangeConsumer handler); - - @Override - Builder using(ClassLoader classLoader); - - Builder using(CompletionCallback completionCallback); - - Builder using(ConnectorCallback connectorCallback); - - @Override - Builder using(OffsetCommitPolicy policy); - - Builder offsetBackingStore(OffsetBackingStore offsetBackingStore); - - @Override - EmbeddedEngine build(); - } - - /** - * Obtain a new {@link Builder} instance that can be used to construct runnable {@link EmbeddedEngine} instances. - * - * @return the new builder; never null - */ - @Deprecated - public static Builder create() { - return new BuilderImpl(); - } - - private static final Logger LOGGER = LoggerFactory.getLogger(EmbeddedEngine.class); - - private final Configuration config; - private final Clock clock; - private final ClassLoader classLoader; - private final DebeziumEngine.ChangeConsumer handler; - private final DebeziumEngine.CompletionCallback completionCallback; - private final DebeziumEngine.ConnectorCallback connectorCallback; - private final AtomicReference runningThread = new AtomicReference<>(); - private final VariableLatch latch = new VariableLatch(0); - private final Converter keyConverter; - private final Converter valueConverter; - private final WorkerConfig workerConfig; - private final CompletionResult completionResult; - private long recordsSinceLastCommit = 0; - private long timeOfLastCommitMillis = 0; - private OffsetCommitPolicy offsetCommitPolicy; - private OffsetBackingStore offsetStore; - - private SourceTask task; - private final Transformations transformations; - - private EmbeddedEngine(Configuration config, ClassLoader classLoader, Clock clock, DebeziumEngine.ChangeConsumer handler, - DebeziumEngine.CompletionCallback completionCallback, DebeziumEngine.ConnectorCallback connectorCallback, - OffsetCommitPolicy offsetCommitPolicy, OffsetBackingStore offsetStore) { - this.offsetStore = offsetStore; - this.config = config; - this.handler = handler; - this.classLoader = classLoader; - this.clock = clock; - this.completionCallback = completionCallback != null ? completionCallback : (success, msg, error) -> { - if (!success) { - LOGGER.error(msg, error); - } - }; - this.connectorCallback = connectorCallback; - this.completionResult = new CompletionResult(); - this.offsetCommitPolicy = offsetCommitPolicy; - - assert this.config != null; - assert this.handler != null; - assert this.classLoader != null; - assert this.clock != null; - keyConverter = config.getInstance(INTERNAL_KEY_CONVERTER_CLASS, Converter.class, () -> this.classLoader); - keyConverter.configure(config.subset(INTERNAL_KEY_CONVERTER_CLASS.name() + ".", true).asMap(), true); - valueConverter = config.getInstance(INTERNAL_VALUE_CONVERTER_CLASS, Converter.class, () -> this.classLoader); - Configuration valueConverterConfig = config; - if (valueConverter instanceof JsonConverter) { - // Make sure that the JSON converter is configured to NOT enable schemas ... - valueConverterConfig = config.edit().with(INTERNAL_VALUE_CONVERTER_CLASS + ".schemas.enable", false).build(); - } - valueConverter.configure(valueConverterConfig.subset(INTERNAL_VALUE_CONVERTER_CLASS.name() + ".", true).asMap(), false); - - transformations = new Transformations(config); - - // Create the worker config, adding extra fields that are required for validation of a worker config - // but that are not used within the embedded engine (since the source records are never serialized) ... - Map embeddedConfig = config.asMap(ALL_FIELDS); - embeddedConfig.put(WorkerConfig.KEY_CONVERTER_CLASS_CONFIG, JsonConverter.class.getName()); - embeddedConfig.put(WorkerConfig.VALUE_CONVERTER_CLASS_CONFIG, JsonConverter.class.getName()); - workerConfig = new EmbeddedConfig(embeddedConfig); - } - - /** - * Determine if this embedded connector is currently running. - * - * @return {@code true} if running, or {@code false} otherwise - */ - public boolean isRunning() { - return this.runningThread.get() != null; - } - - private void fail(String msg) { - fail(msg, null); - } - - private void fail(String msg, Throwable error) { - if (completionResult.hasError()) { - // there's already a recorded failure, so keep the original one and simply log this one - LOGGER.error(msg, error); - return; - } - // don't use the completion callback here because we want to store the error and message only - completionResult.handle(false, msg, error); - } - - private void succeed(String msg) { - // don't use the completion callback here because we want to store the error and message only - completionResult.handle(true, msg, null); - } - - /** - * Run this embedded connector and deliver database changes to the registered {@link Consumer}. This method blocks - * until the connector is stopped. - *

- * First, the method checks to see if this instance is currently {@link #run() running}, and if so immediately - * returns. - *

- * If the configuration is valid, this method starts the connector and starts polling the connector for change - * events. All messages are delivered in batches to the {@link Consumer} registered with this embedded connector. - * The batch size, polling frequency, and other parameters are controlled via configuration settings. This continues - * until this connector is {@link #stop() stopped}. - *

- * Note that there are two ways to stop a connector running on a thread: calling {@link #stop()} from another - * thread, or interrupting the thread (e.g., via {@link ExecutorService#shutdownNow()}). - *

- * This method can be called repeatedly as needed. - */ - @Override - public void run() { - if (runningThread.compareAndSet(null, Thread.currentThread())) { - - final String engineName = config.getString(ENGINE_NAME); - final String connectorClassName = config.getString(CONNECTOR_CLASS); - final Optional connectorCallback = Optional.ofNullable(this.connectorCallback); - // Only one thread can be in this part of the method at a time ... - latch.countUp(); - try { - if (!config.validateAndRecord(CONNECTOR_FIELDS, LOGGER::error)) { - fail("Failed to start connector with invalid configuration (see logs for actual errors)"); - return; - } - - // Instantiate the connector ... - SourceConnector connector = null; - try { - @SuppressWarnings("unchecked") - Class connectorClass = (Class) classLoader.loadClass(connectorClassName); - connector = connectorClass.getDeclaredConstructor().newInstance(); - } - catch (Throwable t) { - fail("Unable to instantiate connector class '" + connectorClassName + "'", t); - return; - } - - // // Instantiate the offset store ... - // final String offsetStoreClassName = config.getString(OFFSET_STORAGE); - // OffsetBackingStore offsetStore = null; - // try { - // @SuppressWarnings("unchecked") - // Class offsetStoreClass = (Class) classLoader - // .loadClass(offsetStoreClassName); - // offsetStore = offsetStoreClass.getDeclaredConstructor().newInstance(); - // } - // catch (Throwable t) { - // fail("Unable to instantiate OffsetBackingStore class '" + offsetStoreClassName + "'", t); - // return; - // } - - // Initialize the offset store ... - try { - offsetStore.configure(workerConfig); - offsetStore.start(); - } - catch (Throwable t) { - fail("Unable to configure and start the '" + offsetStore.getClass().getName() + "' offset backing store", t); - return; - } - - // Set up the offset commit policy ... - if (offsetCommitPolicy == null) { - offsetCommitPolicy = Instantiator.getInstanceWithProperties(config.getString(EmbeddedEngine.OFFSET_COMMIT_POLICY), - () -> getClass().getClassLoader(), config.asProperties()); - } - - // Initialize the connector using a context that does NOT respond to requests to reconfigure tasks ... - ConnectorContext context = new ConnectorContext() { - - @Override - public void requestTaskReconfiguration() { - // Do nothing ... - } - - @Override - public void raiseError(Exception e) { - fail(e.getMessage(), e); - } - - }; - connector.initialize(context); - OffsetStorageWriter offsetWriter = new OffsetStorageWriter(offsetStore, engineName, - keyConverter, valueConverter); - OffsetStorageReader offsetReader = new OffsetStorageReaderImpl(offsetStore, engineName, - keyConverter, valueConverter); - Duration commitTimeout = Duration.ofMillis(config.getLong(OFFSET_COMMIT_TIMEOUT_MS)); - - try { - // Start the connector with the given properties and get the task configurations ... - connector.start(workerConfig.originalsStrings()); - connectorCallback.ifPresent(DebeziumEngine.ConnectorCallback::connectorStarted); - List> taskConfigs = connector.taskConfigs(1); - Class taskClass = connector.taskClass(); - if (taskConfigs.isEmpty()) { - String msg = "Unable to start connector's task class '" + taskClass.getName() + "' with no task configuration"; - fail(msg); - return; - } - task = null; - try { - task = (SourceTask) taskClass.getDeclaredConstructor().newInstance(); - } - catch (IllegalAccessException | InstantiationException t) { - fail("Unable to instantiate connector's task class '" + taskClass.getName() + "'", t); - return; - } - try { - SourceTaskContext taskContext = new SourceTaskContext() { - @Override - public OffsetStorageReader offsetStorageReader() { - return offsetReader; - } - - // Purposely not marking this method with @Override as it was introduced in Kafka 2.x - // and otherwise would break builds based on Kafka 1.x - public Map configs() { - // TODO Auto-generated method stub - return null; - } - }; - task.initialize(taskContext); - task.start(taskConfigs.get(0)); - connectorCallback.ifPresent(DebeziumEngine.ConnectorCallback::taskStarted); - } - catch (Throwable t) { - // Clean-up allocated resources - try { - LOGGER.debug("Stopping the task"); - task.stop(); - } - catch (Throwable tstop) { - LOGGER.info("Error while trying to stop the task"); - } - // Mask the passwords ... - Configuration config = Configuration.from(taskConfigs.get(0)).withMaskedPasswords(); - String msg = "Unable to initialize and start connector's task class '" + taskClass.getName() + "' with config: " - + config; - fail(msg, t); - return; - } - - recordsSinceLastCommit = 0; - Throwable handlerError = null; - try { - timeOfLastCommitMillis = clock.currentTimeInMillis(); - RecordCommitter committer = buildRecordCommitter(offsetWriter, task, commitTimeout); - while (runningThread.get() != null) { - List changeRecords = null; - try { - LOGGER.debug("Embedded engine is polling task for records on thread {}", runningThread.get()); - changeRecords = task.poll(); // blocks until there are values ... - LOGGER.debug("Embedded engine returned from polling task for records"); - } - catch (InterruptedException e) { - // Interrupted while polling ... - LOGGER.debug("Embedded engine interrupted on thread {} while polling the task for records", runningThread.get()); - if (this.runningThread.get() == Thread.currentThread()) { - // this thread is still set as the running thread -> we were not interrupted - // due the stop() call -> probably someone else called the interrupt on us -> - // -> we should raise the interrupt flag - Thread.currentThread().interrupt(); - } - break; - } - catch (RetriableException e) { - LOGGER.info("Retrieable exception thrown, connector will be restarted", e); - // Retriable exception should be ignored by the engine - // and no change records delivered. - // The retry is handled in io.debezium.connector.common.BaseSourceTask.poll() - } - try { - if (changeRecords != null && !changeRecords.isEmpty()) { - LOGGER.debug("Received {} records from the task", changeRecords.size()); - changeRecords = changeRecords.stream() - .map(transformations::transform) - .filter(x -> x != null) - .collect(Collectors.toList()); - } - - if (changeRecords != null && !changeRecords.isEmpty()) { - LOGGER.debug("Received {} transformed records from the task", changeRecords.size()); - - try { - handler.handleBatch(changeRecords, committer); - } - catch (StopConnectorException e) { - break; - } - } - else { - LOGGER.debug("Received no records from the task"); - } - } - catch (Throwable t) { - // There was some sort of unexpected exception, so we should stop work - handlerError = t; - break; - } - } - } - finally { - if (handlerError != null) { - // There was an error in the handler so make sure it's always captured... - fail("Stopping connector after error in the application's handler method: " + handlerError.getMessage(), - handlerError); - } - try { - // First stop the task ... - LOGGER.info("Stopping the task and engine"); - task.stop(); - connectorCallback.ifPresent(DebeziumEngine.ConnectorCallback::taskStopped); - // Always commit offsets that were captured from the source records we actually processed ... - commitOffsets(offsetWriter, commitTimeout, task); - if (handlerError == null) { - // We stopped normally ... - succeed("Connector '" + connectorClassName + "' completed normally."); - } - } - catch (InterruptedException e) { - LOGGER.debug("Interrupted while committing offsets"); - Thread.currentThread().interrupt(); - } - catch (Throwable t) { - fail("Error while trying to stop the task and commit the offsets", t); - } - } - } - catch (Throwable t) { - fail("Error while trying to run connector class '" + connectorClassName + "'", t); - } - finally { - // Close the offset storage and finally the connector ... - try { - offsetStore.stop(); - } - catch (Throwable t) { - fail("Error while trying to stop the offset store", t); - } - finally { - try { - connector.stop(); - connectorCallback.ifPresent(DebeziumEngine.ConnectorCallback::connectorStopped); - } - catch (Throwable t) { - fail("Error while trying to stop connector class '" + connectorClassName + "'", t); - } - } - } - } - finally { - latch.countDown(); - runningThread.set(null); - // after we've "shut down" the engine, fire the completion callback based on the results we collected - completionCallback.handle(completionResult.success(), completionResult.message(), completionResult.error()); - } - } - } - - /** - * Creates a new RecordCommitter that is responsible for informing the engine about the updates to the given batch - * @param offsetWriter the offsetWriter current in use - * @param task the sourcetask - * @param commitTimeout the time in ms until a commit times out - * @return the new recordCommitter to be used for a given batch - */ - protected RecordCommitter buildRecordCommitter(OffsetStorageWriter offsetWriter, SourceTask task, Duration commitTimeout) { - return new RecordCommitter() { - - @Override - public synchronized void markProcessed(SourceRecord record) throws InterruptedException { - task.commitRecord(record); - recordsSinceLastCommit += 1; - offsetWriter.offset((Map) record.sourcePartition(), (Map) record.sourceOffset()); - } - - @Override - public synchronized void markBatchFinished() throws InterruptedException { - maybeFlush(offsetWriter, offsetCommitPolicy, commitTimeout, task); - } - - @Override - public synchronized void markProcessed(SourceRecord record, DebeziumEngine.Offsets sourceOffsets) throws InterruptedException { - SourceRecordOffsets offsets = (SourceRecordOffsets) sourceOffsets; - SourceRecord recordWithUpdatedOffsets = new SourceRecord(record.sourcePartition(), offsets.getOffsets(), record.topic(), - record.kafkaPartition(), record.keySchema(), record.key(), record.valueSchema(), record.value(), - record.timestamp(), record.headers()); - markProcessed(recordWithUpdatedOffsets); - } - - @Override - public DebeziumEngine.Offsets buildOffsets() { - return new SourceRecordOffsets(); - } - }; - } - - /** - * Implementation of {@link DebeziumEngine.Offsets} which can be used to construct a {@link SourceRecord} with its - * offsets. - */ - protected class SourceRecordOffsets implements DebeziumEngine.Offsets { - private HashMap offsets = new HashMap<>(); - - /** - * Performs {@link HashMap#put(Object, Object)} on the offsets map. - * - * @param key key with which to put the value - * @param value value to be put with the key - */ - @Override - public void set(String key, Object value) { - offsets.put(key, value); - } - - /** - * Retrieves the offsets map. - * - * @return HashMap of the offsets - */ - protected HashMap getOffsets() { - return offsets; - } - } - - /** - * Determine if we should flush offsets to storage, and if so then attempt to flush offsets. - * - * @param offsetWriter the offset storage writer; may not be null - * @param policy the offset commit policy; may not be null - * @param commitTimeout the timeout to wait for commit results - * @param task the task which produced the records for which the offsets have been committed - */ - protected void maybeFlush(OffsetStorageWriter offsetWriter, OffsetCommitPolicy policy, Duration commitTimeout, - SourceTask task) - throws InterruptedException { - // Determine if we need to commit to offset storage ... - long timeSinceLastCommitMillis = clock.currentTimeInMillis() - timeOfLastCommitMillis; - if (policy.performCommit(recordsSinceLastCommit, Duration.ofMillis(timeSinceLastCommitMillis))) { - commitOffsets(offsetWriter, commitTimeout, task); - } - } - - /** - * Flush offsets to storage. - * - * @param offsetWriter the offset storage writer; may not be null - * @param commitTimeout the timeout to wait for commit results - * @param task the task which produced the records for which the offsets have been committed - */ - protected void commitOffsets(OffsetStorageWriter offsetWriter, Duration commitTimeout, SourceTask task) - throws InterruptedException { - long started = clock.currentTimeInMillis(); - long timeout = started + commitTimeout.toMillis(); - if (!offsetWriter.beginFlush()) { - return; - } - Future flush = offsetWriter.doFlush(this::completedFlush); - if (flush == null) { - return; // no offsets to commit ... - } - - // Wait until the offsets are flushed ... - try { - flush.get(Math.max(timeout - clock.currentTimeInMillis(), 0), TimeUnit.MILLISECONDS); - // if we've gotten this far, the offsets have been committed so notify the task - task.commit(); - recordsSinceLastCommit = 0; - timeOfLastCommitMillis = clock.currentTimeInMillis(); - } - catch (InterruptedException e) { - LOGGER.warn("Flush of {} offsets interrupted, cancelling", this); - offsetWriter.cancelFlush(); - - if (this.runningThread.get() == Thread.currentThread()) { - // this thread is still set as the running thread -> we were not interrupted - // due the stop() call -> probably someone else called the interrupt on us -> - // -> we should raise the interrupt flag - Thread.currentThread().interrupt(); - throw e; - } - } - catch (ExecutionException e) { - LOGGER.error("Flush of {} offsets threw an unexpected exception: ", this, e); - offsetWriter.cancelFlush(); - } - catch (TimeoutException e) { - LOGGER.error("Timed out waiting to flush {} offsets to storage", this); - offsetWriter.cancelFlush(); - } - } - - protected void completedFlush(Throwable error, Void result) { - if (error != null) { - LOGGER.error("Failed to flush {} offsets to storage: ", this, error); - } - else { - LOGGER.trace("Finished flushing {} offsets to storage", this); - } - } - - /** - * Stop the execution of this embedded connector. This method does not block until the connector is stopped; use - * {@link #await(long, TimeUnit)} for this purpose. - * - * @return {@code true} if the connector was {@link #run() running} and will eventually stop, or {@code false} if it - * was not running when this method is called - * @see #await(long, TimeUnit) - */ - public boolean stop() { - LOGGER.info("Stopping the embedded engine"); - // Signal that the run() method should stop ... - Thread thread = this.runningThread.getAndSet(null); - if (thread != null) { - try { - // Making sure the event source coordinator has enough time to shut down before forcefully stopping it - Duration timeout = Duration.ofMillis(Long - .valueOf(System.getProperty(WAIT_FOR_COMPLETION_BEFORE_INTERRUPT_PROP, Long.toString(WAIT_FOR_COMPLETION_BEFORE_INTERRUPT_DEFAULT.toMillis())))); - LOGGER.info("Waiting for {} for connector to stop", timeout); - latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS); - } - catch (InterruptedException e) { - } - LOGGER.debug("Interrupting the embedded engine's thread {} (already interrupted: {})", thread, thread.isInterrupted()); - // Interrupt the thread in case it is blocked while polling the task for records ... - thread.interrupt(); - return true; - } - return false; - } - - @Override - public void close() throws IOException { - stop(); - } - - /** - * Wait for the connector to complete processing. If the processor is not running, this method returns immediately; - * however, if the processor is {@link #stop() stopped} and restarted before this method is called, this method will - * return only when it completes the second time. - * - * @param timeout the maximum amount of time to wait before returning - * @param unit the unit of time; may not be null - * @return {@code true} if the connector completed within the timeout (or was not running), or {@code false} if it - * is still running when the timeout occurred - * @throws InterruptedException if this thread is interrupted while waiting for the completion of the connector - */ - public boolean await(long timeout, TimeUnit unit) throws InterruptedException { - return latch.await(timeout, unit); - } - - @Override - public String toString() { - return "EmbeddedEngine{id=" + config.getString(ENGINE_NAME) + '}'; - } - - public void runWithTask(Consumer consumer) { - consumer.accept(task); - } - - protected static class EmbeddedConfig extends WorkerConfig { - private static final ConfigDef CONFIG; - - static { - ConfigDef config = baseConfigDef(); - Field.group(config, "file", OFFSET_STORAGE_FILE_FILENAME); - Field.group(config, "kafka", OFFSET_STORAGE_KAFKA_TOPIC); - Field.group(config, "kafka", OFFSET_STORAGE_KAFKA_PARTITIONS); - Field.group(config, "kafka", OFFSET_STORAGE_KAFKA_REPLICATION_FACTOR); - CONFIG = config; - } - - protected EmbeddedConfig(Map props) { - super(CONFIG, props); - } - } -} diff --git a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/EmbeddedEngineExecutorService.java b/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/EmbeddedEngineExecutorService.java deleted file mode 100644 index e7f1fad6..00000000 --- a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/EmbeddedEngineExecutorService.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc; - -import java.io.Closeable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * @author Christian Tzolov - */ -public class EmbeddedEngineExecutorService implements Closeable { - - private static final Log logger = LogFactory.getLog(EmbeddedEngineExecutorService.class); - - private final EmbeddedEngine engine; - private final ExecutorService executor; - - public EmbeddedEngineExecutorService(EmbeddedEngine engine) { - this.engine = engine; - this.executor = Executors.newSingleThreadExecutor(); - } - - public void start() { - logger.info("Start Embedded Engine"); - this.executor.execute(this.engine); - } - - @Override - public void close() { - logger.info("Stop Embedded Engine"); - this.engine.stop(); - this.executor.shutdown(); - } -} diff --git a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/store/MetadataStoreOffsetBackingStore.java b/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/store/MetadataStoreOffsetBackingStore.java deleted file mode 100644 index d75dc505..00000000 --- a/functions/common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/store/MetadataStoreOffsetBackingStore.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.common.cdc.store; - -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.kafka.connect.runtime.WorkerConfig; -import org.apache.kafka.connect.runtime.standalone.StandaloneConfig; -import org.apache.kafka.connect.storage.MemoryOffsetBackingStore; - -import org.springframework.integration.metadata.MetadataStore; - -/** - * @author Christian Tzolov - */ -public class MetadataStoreOffsetBackingStore extends MemoryOffsetBackingStore { - - private MetadataStore metadataStore; - private String offsetStoreName; - - public MetadataStoreOffsetBackingStore(MetadataStore metadataStore) { - this.metadataStore = metadataStore; - } - - @Override - public void configure(WorkerConfig config) { - super.configure(config); - this.offsetStoreName = config.getString(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG); - } - - @Override - public synchronized void start() { - super.start(); - //log.info("Starting FileOffsetBackingStore with file {}", file); - load(); - } - - @Override - public synchronized void stop() { - super.stop(); - // Nothing to do since this doesn't maintain any outstanding connections/data - // log.info("Stopped FileOffsetBackingStore"); - } - - private void load() { - if (this.metadataStore.get("keys") != null) { - String[] keys = this.metadataStore.get("keys").split(","); - for (String keySting : keys) { - String valueString = this.metadataStore.get(keySting); - ByteBuffer key = ByteBuffer.wrap(keySting.getBytes()); - ByteBuffer value = ByteBuffer.wrap(valueString.getBytes()); - this.data.put(key, value); - } - } - } - - @Override - protected void save() { - List keys = new ArrayList<>(); - for (Map.Entry mapEntry : this.data.entrySet()) { - byte[] key = (mapEntry.getKey() != null) ? mapEntry.getKey().array() : null; - byte[] value = (mapEntry.getValue() != null) ? mapEntry.getValue().array() : null; - if (key != null && value != null) { - keys.add(new String(key, StandardCharsets.UTF_8)); - this.metadataStore.put( - new String(key, StandardCharsets.UTF_8), - new String(value, StandardCharsets.UTF_8)); - } - } - this.metadataStore.put("keys", String.join(",", keys)); - } -} diff --git a/functions/common/cdc-debezium-common/src/main/resources/application.properties b/functions/common/cdc-debezium-common/src/main/resources/application.properties deleted file mode 100644 index 6bc13f69..00000000 --- a/functions/common/cdc-debezium-common/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration -spring.cloud.stream.kafka.default.producer.messageKeyExpression=headers['cdc_key'].bytes diff --git a/functions/common/pom.xml b/functions/common/pom.xml index 945a29b1..9e3e6f39 100644 --- a/functions/common/pom.xml +++ b/functions/common/pom.xml @@ -23,8 +23,6 @@ tcp-common twitter-common tensorflow-common - cdc-debezium-common - cdc-debezium-boot-starter xmpp-common diff --git a/functions/function-dependencies/pom.xml b/functions/function-dependencies/pom.xml index 4afc5601..6aa4e9a9 100644 --- a/functions/function-dependencies/pom.xml +++ b/functions/function-dependencies/pom.xml @@ -29,7 +29,7 @@ org.springframework.cloud.fn - cdc-debezium-supplier + debezium-supplier ${project.version} diff --git a/functions/supplier/cdc-debezium-supplier/README.adoc b/functions/supplier/cdc-debezium-supplier/README.adoc deleted file mode 100644 index 628acf5f..00000000 --- a/functions/supplier/cdc-debezium-supplier/README.adoc +++ /dev/null @@ -1,46 +0,0 @@ -# CDC Debezium Supplier - -This module provides a CDC Debezium supplier that can be reused and composed in other applications. -The `Supplier` uses the `Debezium` library. -`cdcSupplier` is implemented as a `java.util.function.Supplier`. -This supplier gives you a reactive stream from CDC sources. The supplier has a signature of `Supplier>>`. -Users have to subscribe to this `Flux` and then receive the data. - -https://en.wikipedia.org/wiki/Change_data_capture[Change Data Capture] (CDC) `source` that captures and streams change events from various databases. -Currently, it supports `MySQL`, `PostgreSQL`, `MongoDB`, `Oracle` and `SQL Server` databases. - -Build upon https://debezium.io/docs/embedded/[Debezium Embedded Connector], the `CDC Source` allows capturing and streaming database changes over different message binders such Apache Kafka, RabbitMQ and all Spring Cloud Stream supporter brokers. - -## Beans for injection - -You can import the `CdcSupplierConfiguration` in the application and then inject the following bean. - -`cdcSupplier` - -You need to inject this as `Supplier>>`. - -You can use `cdcSupplier` as a qualifier when injecting. - -Once injected, you can use the `get` method of the `Supplier` to invoke it and then subscribe to the returned `Flux`. - -## Configuration Options - -All configuration properties are prefixed with `cdc`. -Use the `cdc.config.` prefix to inject native, Debezium properties. Convenient shortcuts for the most frequently used -Debezium properties are available. -Uses `BackingOffsetStore` configuration, based on the https://github.com/spring-cloud/stream-applications/tree/master/functions/common/metadata-store-common[MetadataStore] service. -Later provides various microservices friendly ways for storing the offset metadata. - -For more information on the various options available, please see: - - * link:../../common/cdc-debezium-common/src/main/java/org/springframework/cloud/fn/common/cdc/CdcCommonProperties.java[CdcCommonProperties]. - * link:src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierProperties.java[CdcSupplierProperties]. - -## Examples -See this link:../../../applications/source/cdc-debezium-source/src/test/java/org/springframework/cloud/stream/app/source/cdc[test suite] for the various ways, this supplier is used. - -## Other usage - -See this link:../../../applications/source/cdc-debezium-source/README.adoc[README] where this supplier is used to create a Spring Cloud Stream CDC Source. - -Also check link:../../common/cdc-debezium-boot-starter/README.adoc[README] to see how the core CDC can be used a Spring Boot Starter. diff --git a/functions/supplier/cdc-debezium-supplier/pom.xml b/functions/supplier/cdc-debezium-supplier/pom.xml deleted file mode 100644 index 439be64c..00000000 --- a/functions/supplier/cdc-debezium-supplier/pom.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - 4.0.0 - - - org.springframework.cloud.fn - spring-functions-parent - 4.0.0-SNAPSHOT - ../../spring-functions-parent/pom.xml - - - cdc-debezium-supplier - cdc-debezium-supplier - CDC Debezium Suppliers - - - 1.9.6.Final - - - - - org.springframework.cloud.fn - cdc-debezium-common - ${project.version} - - - io.debezium - debezium-connector-mysql - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-mongodb - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-postgres - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-oracle - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - io.debezium - debezium-connector-sqlserver - - - slf4j-log4j12 - org.slf4j - - - ${version.debezium} - - - diff --git a/functions/supplier/cdc-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierConfiguration.java b/functions/supplier/cdc-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierConfiguration.java deleted file mode 100644 index 2208c844..00000000 --- a/functions/supplier/cdc-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierConfiguration.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.supplier.cdc; - -import java.lang.reflect.Field; -import java.util.Iterator; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.kafka.connect.header.Header; -import org.apache.kafka.connect.source.SourceRecord; -import reactor.core.publisher.EmitterProcessor; -import reactor.core.publisher.Flux; -import reactor.core.publisher.FluxSink; - -import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.fn.common.cdc.CdcCommonConfiguration; -import org.springframework.cloud.fn.common.cdc.EmbeddedEngine; -import org.springframework.cloud.fn.common.cdc.EmbeddedEngineExecutorService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Import; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHeaders; -import org.springframework.messaging.support.MessageBuilder; -import org.springframework.util.ClassUtils; -import org.springframework.util.MimeTypeUtils; - -/** - * CDC source that uses the Debezium Connectors to monitor and record all of the row-level - * changes in the databases. https://debezium.io/docs/connectors - * - * @author Christian Tzolov - */ -@EnableConfigurationProperties(CdcSupplierProperties.class) -@Import(CdcCommonConfiguration.class) -public class CdcSupplierConfiguration implements BeanClassLoaderAware { - - private static final Log logger = LogFactory.getLog(CdcSupplierConfiguration.class); - - /** - * ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL. - */ - public static final String ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL = "org.springframework.kafka.support.KafkaNull"; - - private Object kafkaNull = null; - - @Override - public void setBeanClassLoader(ClassLoader classLoader) { - try { - Class clazz = ClassUtils.forName(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, classLoader); - Field field = clazz.getDeclaredField("INSTANCE"); - this.kafkaNull = field.get(null); - } - catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { - } - } - - @Bean - public Supplier>> cdcSupplier(EmbeddedEngineExecutorService embeddedEngineExecutorService) { - - return () -> emitterProcessor - .doOnSubscribe(subscription -> { - embeddedEngineExecutorService.start(); - }) - .doAfterTerminate(() -> { - logger.info("Proactive shutdown"); - embeddedEngineExecutorService.close(); - }) - .doOnError(throwable -> logger.error(throwable.getMessage(), throwable)); - } - - private EmitterProcessor> emitterProcessor = EmitterProcessor.create(256, false); - - @Bean - public EmbeddedEngineExecutorService embeddedEngineExecutorService( - EmbeddedEngine.Builder embeddedEngineBuilder, - Function valueSerializer, Function keySerializer, - Function recordFlattening, - ObjectMapper mapper, CdcSupplierProperties cdcStreamingEngineProperties) { - - FluxSink> sink = emitterProcessor.sink(FluxSink.OverflowStrategy.BUFFER); - Consumer messageConsumer = sourceRecord -> { - - // When cdc.flattening.deleteHandlingMode=none and cdc.flattening.dropTombstones=false - // then on deletion event an additional sourceRecord is sent with value Null. - // Here we filter out such condition. - if (sourceRecord == null) { - logger.debug("Ignore disabled tombstone events"); - return; - } - - Object cdcJsonPayload = valueSerializer.apply(sourceRecord); - - // When the tombstone event is enabled, Debezium serializes the payload to null (e.g. empty payload) - // while the metadata information is carried through the headers (cdc_key). - // Note: Event for none flattened responses, when the cdc.config.tombstones.on.delete=true - // (default), tombstones are generate by Debezium and handled by the code below. - if (cdcJsonPayload == null) { - cdcJsonPayload = this.kafkaNull; - } - - // If payload is still null ignore the message. - if (cdcJsonPayload == null) { - logger.info("dropped null payload message"); - return; - } - - byte[] key = keySerializer.apply(sourceRecord); - if (key == null) { - logger.warn("Null serialised key for sourceRecord: " + sourceRecord); - key = new byte[0]; - } - - MessageBuilder messageBuilder = MessageBuilder - .withPayload(cdcJsonPayload) -// .setHeader("cdc_key", new String(key)) - .setHeader("cdc_key", key) - .setHeader("cdc_topic", sourceRecord.topic()) - .setHeader(MessageHeaders.CONTENT_TYPE, - (cdcJsonPayload.equals(this.kafkaNull)) ? MimeTypeUtils.TEXT_PLAIN_VALUE - : MimeTypeUtils.APPLICATION_JSON_VALUE); - - if (cdcStreamingEngineProperties.getHeader().isConvertConnectHeaders()) { - // Convert the Connect Headers into Message Headers. - if (sourceRecord.headers() != null && !sourceRecord.headers().isEmpty()) { - Iterator

itr = sourceRecord.headers().iterator(); - while (itr.hasNext()) { - Header header = itr.next(); - messageBuilder.setHeader(header.key(), header.value()); - } - } - } - - if (cdcStreamingEngineProperties.getHeader().isOffset()) { - try { - messageBuilder.setHeader("cdc_offset", - mapper.writeValueAsString(sourceRecord.sourceOffset())); - } - catch (JsonProcessingException e) { - logger.warn("Failed to record cdc_offset header", e); - } - } - - sink.next(messageBuilder.build()); - }; - - EmbeddedEngine engine = embeddedEngineBuilder - .notifying(record -> messageConsumer.accept(recordFlattening.apply(record))) - .build(); - - return new EmbeddedEngineExecutorService(engine); - } -} diff --git a/functions/supplier/cdc-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierProperties.java b/functions/supplier/cdc-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierProperties.java deleted file mode 100644 index 8aa3a071..00000000 --- a/functions/supplier/cdc-debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/cdc/CdcSupplierProperties.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2020-2020 the original author or authors. - * - * Licensed 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 - * - * https://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.springframework.cloud.fn.supplier.cdc; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.validation.annotation.Validated; - -/** - * - * @author Christian Tzolov - */ -@ConfigurationProperties("cdc.stream") -@Validated -public class CdcSupplierProperties { - - /** - * Control what information to be serialized in the outbound message headers. - */ - private Header header = new Header(); - - public Header getHeader() { - return header; - } - - public static class Header { - - /** - * Serializes the source record's offset metadata into the outbound message header under cdc.offset. - */ - private boolean offset = false; - - /** - * When true the {@link org.apache.kafka.connect.header.Header} are converted into message headers with the - * {@link org.apache.kafka.connect.header.Header#key()} as name and {@link org.apache.kafka.connect.header.Header#value()}. - */ - private boolean convertConnectHeaders = true; - - public boolean isOffset() { - return offset; - } - - public void setOffset(boolean offset) { - this.offset = offset; - } - - public boolean isConvertConnectHeaders() { - return convertConnectHeaders; - } - - public void setConvertConnectHeaders(boolean convertConnectHeaders) { - this.convertConnectHeaders = convertConnectHeaders; - } - } -} diff --git a/functions/supplier/cdc-debezium-supplier/src/main/resources/application.properties b/functions/supplier/cdc-debezium-supplier/src/main/resources/application.properties deleted file mode 100644 index 6bc13f69..00000000 --- a/functions/supplier/cdc-debezium-supplier/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration -spring.cloud.stream.kafka.default.producer.messageKeyExpression=headers['cdc_key'].bytes diff --git a/functions/supplier/debezium-supplier/pom.xml b/functions/supplier/debezium-supplier/pom.xml new file mode 100644 index 00000000..089f14f6 --- /dev/null +++ b/functions/supplier/debezium-supplier/pom.xml @@ -0,0 +1,181 @@ + + + 4.0.0 + + + org.springframework.cloud.fn + spring-functions-parent + 4.0.0-SNAPSHOT + ../../spring-functions-parent/pom.xml + + + debezium-supplier + debezium-supplier + Debezium Supplier + + + 2.2.0.Final + 2.4.2.Final + + + + + io.debezium + debezium-embedded + ${version.debezium} + + + slf4j-reload4j + org.slf4j + + + slf4j-log4j12 + org.slf4j + + + + + + + io.debezium + debezium-connector-mysql + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + io.debezium + debezium-connector-mongodb + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + io.debezium + debezium-connector-postgres + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + io.debezium + debezium-connector-oracle + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + io.debezium + debezium-connector-sqlserver + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + io.debezium + debezium-connector-db2 + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + io.debezium + debezium-connector-vitess + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + + + + io.debezium + debezium-connector-spanner + ${version.debezium} + + + slf4j-log4j12 + org.slf4j + + + true + + + + + io.apicurio + apicurio-registry-utils-converter + ${apicurio.version} + + + io.apicurio + apicurio-registry-client + ${apicurio.version} + + + + + com.zaxxer + HikariCP + 4.0.3 + test + + + org.springframework + spring-jdbc + test + + + + + + maven-surefire-plugin + 3.0.0 + + integration + + + + + diff --git a/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumEngineAutoConfiguration.java b/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumEngineAutoConfiguration.java new file mode 100644 index 00000000..24453708 --- /dev/null +++ b/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumEngineAutoConfiguration.java @@ -0,0 +1,183 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium; + +import java.time.Clock; +import java.time.Duration; +import java.util.function.Consumer; + +import io.debezium.engine.ChangeEvent; +import io.debezium.engine.DebeziumEngine; +import io.debezium.engine.DebeziumEngine.CompletionCallback; +import io.debezium.engine.DebeziumEngine.ConnectorCallback; +import io.debezium.engine.spi.OffsetCommitPolicy; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; + +/** + * DebeziumEngine auto-configuration. + * + * The engine configuration is entirely standalone and only talks with the source system; Applications using the engine + * auto-configuration simply provides a {@link Consumer consumer function} implementation to which the engine will pass + * all records containing database change events. + *

+ * With the engine, the application that runs the connector assumes all responsibility for fault tolerance, scalability, + * and durability. Additionally, applications must specify how the engine can store its relational database schema + * history and offsets. By default, this information will be stored in memory and will thus be lost upon application + * restart. + * + * @author Christian Tzolov + */ +@AutoConfiguration +@EnableConfigurationProperties(DebeziumProperties.class) +public class DebeziumEngineAutoConfiguration { + + private static final Log logger = LogFactory.getLog(DebeziumEngineAutoConfiguration.class); + + /** + * The fully-qualified class name of the commit policy type. The default is a periodic commit policy based upon time + * intervals. + * @param properties The 'debezium.properties.offset.flush.interval.ms' configuration is compulsory for the Periodic + * policy type. The ALWAYS and DEFAULT doesn't require properties. + */ + @Bean + @ConditionalOnMissingBean + public OffsetCommitPolicy offsetCommitPolicy(DebeziumProperties properties) { + + switch (properties.getOffsetCommitPolicy()) { + case PERIODIC: + return OffsetCommitPolicy.periodic(properties.getDebeziumNativeConfiguration()); + case ALWAYS: + return OffsetCommitPolicy.always(); + case DEFAULT: + default: + return NULL_OFFSET_COMMIT_POLICY; + } + } + + /** + * Use the specified clock when needing to determine the current time. Defaults to {@link Clock#systemDefaultZone() + * system clock}, but you can override the Bean in your configuration with you {@link Clock implementation}. Returns + * @return Clock for the system default zone. + */ + @Bean + @ConditionalOnMissingBean + public Clock debeziumClock() { + return Clock.systemDefaultZone(); + } + + /** + * When the engine's {@link DebeziumEngine#run()} method completes, call the supplied function with the results. + * @return Default completion callback that logs the completion status. The bean can be overridden in custom + * implementation. + */ + @Bean + @ConditionalOnMissingBean + public CompletionCallback completionCallback() { + return DEFAULT_COMPLETION_CALLBACK; + } + + /** + * During the engine run, provides feedback about the different stages according to the completion state of each + * component running within the engine (connectors, tasks etc). The bean can be overridden in custom implementation. + */ + @Bean + @ConditionalOnMissingBean + public ConnectorCallback connectorCallback() { + return DEFAULT_CONNECTOR_CALLBACK; + } + + @Bean + public DebeziumEngine debeziumEngine(Consumer> changeEventConsumer, + OffsetCommitPolicy offsetCommitPolicy, CompletionCallback completionCallback, + ConnectorCallback connectorCallback, DebeziumProperties properties, Clock debeziumClock) { + + DebeziumEngine> debeziumEngine = DebeziumEngine + .create(properties.getFormat().serializationFormat()) + .using(properties.getDebeziumNativeConfiguration()) + .using(debeziumClock) + .using(completionCallback) + .using(connectorCallback) + .using((offsetCommitPolicy != NULL_OFFSET_COMMIT_POLICY) ? offsetCommitPolicy : null) + .notifying(changeEventConsumer) + .build(); + + + return debeziumEngine; + } + + /** + * A callback function to be notified when the connector completes. + */ + private static final CompletionCallback DEFAULT_COMPLETION_CALLBACK = new CompletionCallback() { + @Override + public void handle(boolean success, String message, Throwable error) { + logger.info(String.format("Debezium Engine completed with success:%s, message:%s ", success, message), + error); + } + }; + + /** + * Callback function which informs users about the various stages a connector goes through during startup. + */ + private static final ConnectorCallback DEFAULT_CONNECTOR_CALLBACK = new ConnectorCallback() { + + /** + * Called after a connector has been successfully started by the engine. + */ + public void connectorStarted() { + logger.info("Connector Started!"); + }; + + /** + * Called after a connector has been successfully stopped by the engine. + */ + public void connectorStopped() { + logger.info("Connector Stopped!"); + } + + /** + * Called after a connector task has been successfully started by the engine. + */ + public void taskStarted() { + logger.info("Connector Task Started!"); + } + + /** + * Called after a connector task has been successfully stopped by the engine. + */ + public void taskStopped() { + logger.info("Connector Task Stopped!"); + } + + }; + + /** + * The policy that defines when the offsets should be committed to offset storage. + */ + private static final OffsetCommitPolicy NULL_OFFSET_COMMIT_POLICY = new OffsetCommitPolicy() { + @Override + public boolean performCommit(long numberOfMessagesSinceLastCommit, Duration timeSinceLastCommit) { + throw new UnsupportedOperationException("Unimplemented method 'performCommit'"); + } + }; +} diff --git a/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumProperties.java b/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumProperties.java new file mode 100644 index 00000000..640ee9ca --- /dev/null +++ b/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumProperties.java @@ -0,0 +1,139 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import io.debezium.engine.format.SerializationFormat; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * @author Christian Tzolov + */ +@ConfigurationProperties("debezium") +public class DebeziumProperties { + + public enum DebeziumFormat { + /** + * JSON change event format. + */ + JSON(io.debezium.engine.format.JsonByteArray.class, "application/json"), + /** + * AVRO change event format. + */ + AVRO(io.debezium.engine.format.Avro.class, "application/avro"), + /** + * ProtoBuf change event format. + */ + PROTOBUF(io.debezium.engine.format.Protobuf.class, "application/x-protobuf"),; + + private final Class> serializationFormat; + private final String contentType; + + DebeziumFormat(Class> serializationFormat, String contentType) { + this.serializationFormat = serializationFormat; + this.contentType = contentType; + } + + public Class> serializationFormat() { + return serializationFormat; + } + + public final String contentType() { + return contentType; + } + }; + + /** + * Spring pass-trough wrapper for debezium configuration properties. All properties with a 'debezium.properties.*' + * prefix are native Debezium properties. + */ + private Map properties = new HashMap<>(); + + /** + * Change Event message content format. Defaults to 'JSON'. + */ + private DebeziumFormat format = DebeziumFormat.JSON; + + /** + * Copy Change Event headers into Message headers. + */ + private boolean copyHeaders = true; + + /** + * The policy that defines when the offsets should be committed to offset storage. + */ + private DebeziumOffsetCommitPolicy offsetCommitPolicy = DebeziumOffsetCommitPolicy.DEFAULT; + + public Map getProperties() { + return properties; + } + + public DebeziumFormat getFormat() { + return format; + } + + public void setFormat(DebeziumFormat format) { + this.format = format; + } + + public boolean isCopyHeaders() { + return copyHeaders; + } + + public void setCopyHeaders(boolean copyHeaders) { + this.copyHeaders = copyHeaders; + } + + public enum DebeziumOffsetCommitPolicy { + /** + * Commits offsets as frequently as possible. This may result in reduced performance, but it has the least + * potential for seeing source records more than once upon restart. + */ + ALWAYS, + /** + * Commits offsets no more than the specified time period. If the specified time is less than {@code 0} then the + * policy will behave as ALWAYS policy. Requires the 'debezium.properties.offset.flush.interval.ms' native property + * to be set. + */ + PERIODIC, + /** + * Uses the default Debezium engine policy (PERIODIC). + */ + DEFAULT; + } + + public DebeziumOffsetCommitPolicy getOffsetCommitPolicy() { + return offsetCommitPolicy; + } + + public void setOffsetCommitPolicy(DebeziumOffsetCommitPolicy offsetCommitPolicy) { + this.offsetCommitPolicy = offsetCommitPolicy; + } + + /** + * Converts the Spring Framework "debezium.properties.*" properties into native Debezium configuration. + */ + public Properties getDebeziumNativeConfiguration() { + Properties outProps = new java.util.Properties(); + outProps.putAll(this.getProperties()); + return outProps; + } +} diff --git a/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumReactiveConsumerConfiguration.java b/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumReactiveConsumerConfiguration.java new file mode 100644 index 00000000..fee3e494 --- /dev/null +++ b/functions/supplier/debezium-supplier/src/main/java/org/springframework/cloud/fn/supplier/debezium/DebeziumReactiveConsumerConfiguration.java @@ -0,0 +1,165 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium; + +import java.lang.reflect.Field; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import java.util.function.Supplier; + +import io.debezium.engine.ChangeEvent; +import io.debezium.engine.DebeziumEngine; +import io.debezium.engine.Header; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Sinks; + +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHeaders; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.util.ClassUtils; +import org.springframework.util.MimeTypeUtils; + +/** + * + * @author Christian Tzolov + * @author Artem Bilan + */ +@Configuration +@EnableConfigurationProperties(DebeziumProperties.class) +public class DebeziumReactiveConsumerConfiguration implements BeanClassLoaderAware { + + private static final Log logger = LogFactory.getLog(DebeziumReactiveConsumerConfiguration.class); + /** + * ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL. + */ + public static final String ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL = "org.springframework.kafka.support.KafkaNull"; + + private Object kafkaNull = null; + + @Override + public void setBeanClassLoader(ClassLoader classLoader) { + try { + Class clazz = ClassUtils.forName(ORG_SPRINGFRAMEWORK_KAFKA_SUPPORT_KAFKA_NULL, classLoader); + Field field = clazz.getDeclaredField("INSTANCE"); + this.kafkaNull = field.get(null); + } + catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { + } + } + + /** + * Reactive Streams, single subscriber, sink used to push down the change event signals received from the Debezium + * Engine. + */ + private final Sinks.Many> eventSink = Sinks.many().unicast().onBackpressureError(); + + /** + * Debezium Engine is designed to be submitted to an {@link ExecutorService} for execution by a single thread, and a + * running connector can be stopped either by calling {@link #stop()} from another thread or by interrupting the + * running thread (e.g., as is the case with {@link ExecutorService#shutdownNow()}). + */ + private final ExecutorService debeziumExecutor = Executors.newSingleThreadExecutor(); + + @Bean + public Supplier>> debeziumSupplier(DebeziumEngine debeziumEngine) { + return () -> this.eventSink.asFlux() + .doOnRequest(r -> debeziumExecutor.execute(debeziumEngine)) + .doOnTerminate(debeziumExecutor::shutdownNow); + } + + @Bean + @ConditionalOnMissingBean + public Consumer> changeEventConsumer(DebeziumProperties properties) { + + return new ChangeEventConsumer(properties.getFormat().contentType(), properties.isCopyHeaders(), + this.eventSink); + } + + /** + * Format-agnostic change event consumer. + */ + private final class ChangeEventConsumer implements Consumer> { + + private final String contentType; + private final boolean copyHeaders; + private final Sinks.Many> eventSink; + + private ChangeEventConsumer(String contentType, boolean copyHeaders, Sinks.Many> eventSink) { + this.contentType = contentType; + this.copyHeaders = copyHeaders; + this.eventSink = eventSink; + } + + @Override + public void accept(ChangeEvent changeEvent) { + if (logger.isDebugEnabled()) { + logger.debug("[Debezium Event]: " + changeEvent.key()); + } + + Object key = changeEvent.key(); + Object payload = changeEvent.value(); + String destination = changeEvent.destination(); + + // When the tombstone event is enabled, Debezium serializes the payload to null (e.g. empty payload) + // while the metadata information is carried through the headers (debezium_key). + // Note: Event for none flattened responses, when the debezium.properties.tombstones.on.delete=true + // (default), tombstones are generate by Debezium and handled by the code below. + if (payload == null) { + payload = DebeziumReactiveConsumerConfiguration.this.kafkaNull; + } + + // If payload is still null ignore the message. + if (payload == null) { + logger.info("Dropped null payload message"); + return; + } + + MessageBuilder messageBuilder = MessageBuilder + .withPayload(payload) + .setHeader("debezium_key", key) + .setHeader("debezium_destination", destination) + .setHeader(MessageHeaders.CONTENT_TYPE, + (payload.equals(DebeziumReactiveConsumerConfiguration.this.kafkaNull)) + ? MimeTypeUtils.TEXT_PLAIN_VALUE + : this.contentType); + + if (this.copyHeaders) { + List> headers = changeEvent.headers(); + if (headers != null && !headers.isEmpty()) { + Iterator> itr = headers.iterator(); + while (itr.hasNext()) { + Header header = itr.next(); + messageBuilder.setHeader(header.getKey(), header.getValue()); + } + } + } + + this.eventSink.tryEmitNext(messageBuilder.build()); + } + } + +} diff --git a/functions/supplier/debezium-supplier/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/functions/supplier/debezium-supplier/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 00000000..a85c0324 --- /dev/null +++ b/functions/supplier/debezium-supplier/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1 @@ +org.springframework.cloud.fn.supplier.debezium.DebeziumEngineAutoConfiguration diff --git a/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/TestJdbcTemplateConfiguration.java b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/TestJdbcTemplateConfiguration.java new file mode 100644 index 00000000..9ff97e61 --- /dev/null +++ b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/TestJdbcTemplateConfiguration.java @@ -0,0 +1,55 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium; + +import javax.sql.DataSource; + +import com.zaxxer.hikari.HikariDataSource; + +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * + * @author Christian Tzolov + */ +@Configuration +public class TestJdbcTemplateConfiguration { + @Bean + public JdbcTemplate myJdbcTemplate(DataSource dataSource) { + return new JdbcTemplate(dataSource); + } + + @Bean + @Primary + @ConfigurationProperties("app.datasource") + public DataSourceProperties dataSourceProperties() { + return new DataSourceProperties(); + } + + @Bean + public HikariDataSource dataSource(DataSourceProperties dataSourceProperties) { + return dataSourceProperties.initializeDataSourceBuilder() + .type(HikariDataSource.class) + .build(); + } + +} diff --git a/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/custom/DebeziumEngineAutoConfigurationTest.java b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/custom/DebeziumEngineAutoConfigurationTest.java new file mode 100644 index 00000000..242c33ae --- /dev/null +++ b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/custom/DebeziumEngineAutoConfigurationTest.java @@ -0,0 +1,180 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium.custom; + +import java.io.File; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.function.Consumer; + +import io.debezium.engine.ChangeEvent; +import io.debezium.engine.DebeziumEngine; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.cloud.fn.supplier.debezium.TestJdbcTemplateConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.jdbc.JdbcTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +/** + * This test illustrate how to leverage the DebeziumEngineAutoConfiguration to build a supplier function with a custom + * change event Consumer. + * + * @author Christian Tzolov + */ +@Tag("integration") +@Testcontainers +public class DebeziumEngineAutoConfigurationTest { + private static final Log logger = LogFactory.getLog(DebeziumEngineAutoConfigurationTest.class); + + private static final String DATABASE_NAME = "inventory"; + public static final String IMAGE_TAG = "2.2.0.Final"; + public static final String DEBEZIUM_EXAMPLE_MYSQL_IMAGE = "debezium/example-mysql:" + IMAGE_TAG; + + @TempDir + static File anotherTempDir; + + @Container + static GenericContainer debeziumMySQL = new GenericContainer<>(DEBEZIUM_EXAMPLE_MYSQL_IMAGE) + .withEnv("MYSQL_ROOT_PASSWORD", "debezium") + .withEnv("MYSQL_USER", "mysqluser") + .withEnv("MYSQL_PASSWORD", "mysqlpw") + .withExposedPorts(3306); + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(DebeziumCustomConsumerApplication.class) + .withPropertyValues( + "spring.datasource.type=com.zaxxer.hikari.HikariDataSource", + + "debezium.properties.offset.storage=org.apache.kafka.connect.storage.FileOffsetBackingStore", + "debezium.properties.offset.storage.file.filename=" + anotherTempDir.getAbsolutePath() + + "offsets.dat", + "debezium.properties.offset.flush.interval.ms=60000", + + "debezium.properties.schema.history.internal=io.debezium.storage.file.history.FileSchemaHistory", // new + "debezium.properties.schema.history.internal.file.filename=" + anotherTempDir.getAbsolutePath() + + "schemahistory.dat", // new + + "debezium.properties.topic.prefix=my-topic", // new + + "debezium.properties.name=my-sql-connector", + "debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector", + + "debezium.properties.database.user=debezium", + "debezium.properties.database.password=dbz", + "debezium.properties.database.hostname=localhost", + "debezium.properties.database.port=" + debeziumMySQL.getMappedPort(3306), + "debezium.properties.database.server.id=85744", + "debezium.properties.database.server.name=my-app-connector", + "debezium.properties.database.history=io.debezium.relational.history.MemoryDatabaseHistory", + + // JdbcTemplate configuration + String.format("app.datasource.url=jdbc:mysql://localhost:%d/%s?enabledTLSProtocols=TLSv1.2", + debeziumMySQL.getMappedPort(3306), DATABASE_NAME), + "app.datasource.username=root", + "app.datasource.password=debezium", + "app.datasource.driver-class-name=com.mysql.cj.jdbc.Driver", + "app.datasource.type=com.zaxxer.hikari.HikariDataSource"); + + @Test + public void consumerTest() { + + logger.info("Temp dir: " + anotherTempDir.getAbsolutePath()); + + contextRunner + .withPropertyValues( + // Flattering: + // https://debezium.io/documentation/reference/stable/transformations/event-flattening.html + "debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.drop.tombstones=false", + "debezium.properties.transforms.unwrap.delete.handling.mode=rewrite", + "debezium.properties.transforms.unwrap.add.fields=name,db") + .run(context -> { + JdbcTemplate jdbcTemplate = context.getBean(JdbcTemplate.class); + + DebeziumCustomConsumerApplication.TestDebeziumConsumer testConsumer = context + .getBean(DebeziumCustomConsumerApplication.TestDebeziumConsumer.class); + jdbcTemplate.update( + "insert into `customers`(`first_name`,`last_name`,`email`) " + + "VALUES('Test666', 'Test666', 'Test666@spring.org')"); + JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "customers", "first_name = ?", "Test666"); + + await().atMost(Duration.ofSeconds(30)) + .untilAsserted(() -> assertThat(testConsumer.recordList).hasSizeGreaterThanOrEqualTo(52)); + }); + } + + @SpringBootConfiguration + @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, MongoAutoConfiguration.class }) + @Import(TestJdbcTemplateConfiguration.class) + public static class DebeziumCustomConsumerApplication { + + @Bean + public EmbeddedEngineExecutorService embeddedEngine(DebeziumEngine debeziumEngine) { + return new EmbeddedEngineExecutorService(debeziumEngine); + } + + @Bean + public Consumer> customConsumer() { + return new TestDebeziumConsumer(); + } + + /** + * Custom, test, change event Consumer. + */ + public static class TestDebeziumConsumer implements Consumer> { + + public Map keyValue = new HashMap<>(); + + public List> recordList = new CopyOnWriteArrayList<>(); + + public TestDebeziumConsumer() { + } + + @Override + public void accept(ChangeEvent changeEvent) { + if (changeEvent != null) { // ignore null records + recordList.add(changeEvent); + keyValue.put(changeEvent.key(), changeEvent.value()); + System.out.println("SIZE=" + recordList.size()); + System.out.println("[Debezium Event]: " + changeEvent.toString()); + } + } + } + } + +} diff --git a/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/custom/EmbeddedEngineExecutorService.java b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/custom/EmbeddedEngineExecutorService.java new file mode 100644 index 00000000..ff599384 --- /dev/null +++ b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/custom/EmbeddedEngineExecutorService.java @@ -0,0 +1,84 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium.custom; + +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; + +import io.debezium.engine.DebeziumEngine; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.context.SmartLifecycle; + +/** + * The Debezium Engine is designed to be submitted to an {@link Executor} or {@link ExecutorService} for execution by a + * single thread, and a running connector can be stopped either by calling {@link #stop()} from another thread or by + * interrupting the running thread (e.g., as is the case with {@link ExecutorService#shutdownNow()}). + * + * The EmbeddedEngineExecutorService provides a sample ExecutorService implementation aligned with the Spring lifecycle. + * + * Note that the DebeziumReactiveConsumerConfiguration embeds an ExecutorService as part of the + * Supplier<Flux<Message<?>>> configuration. + * + * @author Christian Tzolov + */ +public class EmbeddedEngineExecutorService implements SmartLifecycle, AutoCloseable { + + private static final Log logger = LogFactory.getLog(EmbeddedEngineExecutorService.class); + + private final DebeziumEngine engine; + private final ExecutorService executor; + private final AtomicBoolean running = new AtomicBoolean(false); + + public EmbeddedEngineExecutorService(DebeziumEngine engine) { + this.engine = engine; + this.executor = Executors.newSingleThreadExecutor(); + } + + @Override + public void start() { + logger.info("Start Embedded Engine"); + this.executor.execute(this.engine); + this.running.set(true); + } + + @Override + public void stop() { + this.close(); + } + + @Override + public void close() { + logger.info("Stop Embedded Engine"); + try { + this.engine.close(); + this.running.set(false); + } + catch (IOException e) { + logger.warn("Failed to close the Debezium Engine:", e); + } + this.executor.shutdown(); + } + + @Override + public boolean isRunning() { + return this.running.get(); + } +} diff --git a/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/supplier/DebeziumSupplierTest.java b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/supplier/DebeziumSupplierTest.java new file mode 100644 index 00000000..1851875c --- /dev/null +++ b/functions/supplier/debezium-supplier/src/test/java/org/springframework/cloud/fn/supplier/debezium/supplier/DebeziumSupplierTest.java @@ -0,0 +1,178 @@ +/* + * Copyright 2023-2023 the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.fn.supplier.debezium.supplier; + +import java.util.function.Supplier; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.fn.supplier.debezium.DebeziumReactiveConsumerConfiguration; +import org.springframework.cloud.fn.supplier.debezium.TestJdbcTemplateConfiguration; +import org.springframework.context.annotation.Import; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.messaging.Message; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, properties = { + "spring.cloud.function.definition=debeziumSupplier", + + // https://debezium.io/documentation/reference/2.2/transformations/event-flattening.html + "debezium.properties.transforms=unwrap", + "debezium.properties.transforms.unwrap.type=io.debezium.transforms.ExtractNewRecordState", + "debezium.properties.transforms.unwrap.drop.tombstones=true", + "debezium.properties.transforms.unwrap.delete.handling.mode=rewrite", + "debezium.properties.transforms.unwrap.add.fields=name,db,op,table", + + "debezium.properties.schema.history.internal=io.debezium.relational.history.MemorySchemaHistory", + "debezium.properties.offset.storage=org.apache.kafka.connect.storage.MemoryOffsetBackingStore", + + // Drop schema from the message payload. + "debezium.properties.key.converter.schemas.enable=false", + "debezium.properties.value.converter.schemas.enable=false", + + "debezium.properties.topic.prefix=my-topic", + "debezium.properties.name=my-connector", + "debezium.properties.database.server.id=85744", + "debezium.properties.database.server.name=my-app-connector", + "debezium.properties.connector.class=io.debezium.connector.mysql.MySqlConnector", + "debezium.properties.database.user=debezium", + "debezium.properties.database.password=dbz", + "debezium.properties.database.hostname=localhost", + + "debezium.properties.table.include.list=inventory.customers, inventory.addresses", + + // JdbcTemplate config. + "app.datasource.username=root", + "app.datasource.password=debezium", + "app.datasource.driver-class-name=com.mysql.cj.jdbc.Driver", + "app.datasource.type=com.zaxxer.hikari.HikariDataSource" +}) +@Testcontainers +public class DebeziumSupplierTest { + + public static final String IMAGE_TAG = "2.2.0.Final"; + public static final String DEBEZIUM_EXAMPLE_MYSQL_IMAGE = "debezium/example-mysql:" + IMAGE_TAG; + + @Container + static GenericContainer debeziumMySQL = new GenericContainer<>(DEBEZIUM_EXAMPLE_MYSQL_IMAGE) + .withEnv("MYSQL_ROOT_PASSWORD", "debezium") + .withEnv("MYSQL_USER", "mysqluser") + .withEnv("MYSQL_PASSWORD", "mysqlpw") + .withExposedPorts(3306); + + @DynamicPropertySource + static void mysqlDbProperties(DynamicPropertyRegistry registry) { + registry.add("debezium.properties.database.port", () -> debeziumMySQL.getMappedPort(3306)); + registry.add("app.datasource.url", + () -> String.format("jdbc:mysql://localhost:%d/%s?enabledTLSProtocols=TLSv1.2", + debeziumMySQL.getMappedPort(3306), "inventory")); // JdbcTemplate config. + } + + private ObjectMapper objectMapper = new ObjectMapper(); + + @Autowired + private Supplier>> debeziumSupplier; + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Test + void testDebeziumSupplier() { + + jdbcTemplate.update( + "INSERT INTO `customers`(`first_name`,`last_name`,`email`) VALUES('Test666', 'Test666', 'Test666@spring.org')"); + // jdbcTemplate.update("DELETE FROM `customers` WHERE `first_name` = ?", "Test666"); + + Flux> messageFlux = this.debeziumSupplier.get(); + + // Message size should correspond to the number of insert statements in: + // https://github.com/debezium/container-images/blob/main/examples/mysql/2.2/inventory.sql + // filtered by Customers and Addresses table. + StepVerifier.create(messageFlux) + .expectNextCount(16) // Skip the DDL transaction logs. + + // Customers table + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":1001,\"first_name\":\"Sally\",\"last_name\":\"Thomas\",\"email\":\"sally.thomas@acme.com\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"customers\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":1002,\"first_name\":\"George\",\"last_name\":\"Bailey\",\"email\":\"gbailey@foobar.com\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"customers\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":1003,\"first_name\":\"Edward\",\"last_name\":\"Walker\",\"email\":\"ed@walker.com\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"customers\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":1004,\"first_name\":\"Anne\",\"last_name\":\"Kretchmar\",\"email\":\"annek@noanswer.org\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"customers\",\"__deleted\":\"false\"}")) + + // NEW Customer Insert + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":1005,\"first_name\":\"Test666\",\"last_name\":\"Test666\",\"email\":\"Test666@spring.org\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"customers\",\"__deleted\":\"false\"}")) + + // Addresses table + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":10,\"customer_id\":1001,\"street\":\"3183 Moore Avenue\",\"city\":\"Euless\",\"state\":\"Texas\",\"zip\":\"76036\",\"type\":\"SHIPPING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":11,\"customer_id\":1001,\"street\":\"2389 Hidden Valley Road\",\"city\":\"Harrisburg\",\"state\":\"Pennsylvania\",\"zip\":\"17116\",\"type\":\"BILLING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":12,\"customer_id\":1002,\"street\":\"281 Riverside Drive\",\"city\":\"Augusta\",\"state\":\"Georgia\",\"zip\":\"30901\",\"type\":\"BILLING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":13,\"customer_id\":1003,\"street\":\"3787 Brownton Road\",\"city\":\"Columbus\",\"state\":\"Mississippi\",\"zip\":\"39701\",\"type\":\"SHIPPING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":14,\"customer_id\":1003,\"street\":\"2458 Lost Creek Road\",\"city\":\"Bethlehem\",\"state\":\"Pennsylvania\",\"zip\":\"18018\",\"type\":\"SHIPPING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":15,\"customer_id\":1003,\"street\":\"4800 Simpson Square\",\"city\":\"Hillsdale\",\"state\":\"Oklahoma\",\"zip\":\"73743\",\"type\":\"BILLING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .assertNext((message) -> assertThat(payloadString(message)) + .isEqualTo( + "{\"id\":16,\"customer_id\":1004,\"street\":\"1289 University Hill Road\",\"city\":\"Canehill\",\"state\":\"Arkansas\",\"zip\":\"72717\",\"type\":\"LIVING\",\"__name\":\"my-topic\",\"__db\":\"inventory\",\"__op\":\"r\",\"__table\":\"addresses\",\"__deleted\":\"false\"}")) + .thenCancel() + .verify(); + + } + + private String payloadString(Message message) { + return new String((byte[]) message.getPayload()); + } + + @SpringBootApplication + @EnableAutoConfiguration(exclude = { MongoAutoConfiguration.class }) + @Import({DebeziumReactiveConsumerConfiguration.class, TestJdbcTemplateConfiguration.class}) + static class DebeziumSupplierTestApplication { + } + +} diff --git a/functions/common/cdc-debezium-boot-starter/src/test/resources/logback-test.xml b/functions/supplier/debezium-supplier/src/test/resources/logback-test.xml similarity index 98% rename from functions/common/cdc-debezium-boot-starter/src/test/resources/logback-test.xml rename to functions/supplier/debezium-supplier/src/test/resources/logback-test.xml index 96fa1fcd..227674db 100644 --- a/functions/common/cdc-debezium-boot-starter/src/test/resources/logback-test.xml +++ b/functions/supplier/debezium-supplier/src/test/resources/logback-test.xml @@ -27,4 +27,4 @@ - \ No newline at end of file + diff --git a/functions/supplier/pom.xml b/functions/supplier/pom.xml index 7b9f3d34..4a7a042b 100644 --- a/functions/supplier/pom.xml +++ b/functions/supplier/pom.xml @@ -26,7 +26,7 @@ websocket-supplier s3-supplier twitter-supplier - cdc-debezium-supplier + debezium-supplier syslog-supplier xmpp-supplier zeromq-supplier diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-docker.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-docker.properties index 2bbc3b8a..1c2011b6 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-docker.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-docker.properties @@ -1,4 +1,4 @@ -source.cdc-debezium=docker:springcloudstream/cdc-debezium-source-kafka:@apps.docker.tag@ +source.debezium=docker:springcloudstream/debezium-source-kafka:@apps.docker.tag@ source.file=docker:springcloudstream/file-source-kafka:@apps.docker.tag@ source.ftp=docker:springcloudstream/ftp-source-kafka:@apps.docker.tag@ source.http=docker:springcloudstream/http-source-kafka:@apps.docker.tag@ diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-harbor.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-harbor.properties index a8cfd66a..4a6a9879 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-harbor.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-harbor.properties @@ -1,4 +1,4 @@ -source.cdc-debezium=docker:projects.registry.vmware.com/springcloudstream/cdc-debezium-source-kafka:@apps.harbor.version@ +source.debezium=docker:projects.registry.vmware.com/springcloudstream/debezium-source-kafka:@apps.harbor.version@ source.file=docker:projects.registry.vmware.com/springcloudstream/file-source-kafka:@apps.harbor.version@ source.ftp=docker:projects.registry.vmware.com/springcloudstream/ftp-source-kafka:@apps.harbor.version@ source.http=docker:projects.registry.vmware.com/springcloudstream/http-source-kafka:@apps.harbor.version@ diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven-repo-url.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven-repo-url.properties index 6f49c2b1..9385cf15 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven-repo-url.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven-repo-url.properties @@ -1,5 +1,5 @@ -source.cdc-debezium=https://@repo-spring-io@/org/springframework/cloud/stream/app/cdc-debezium-source-kafka/@apps.version@/cdc-debezium-source-kafka-@apps.version@.jar -source.cdc-debezium.metadata=https://@repo-spring-io@/org/springframework/cloud/stream/app/cdc-debezium-source-kafka/@apps.version@/cdc-debezium-source-kafka-@apps.version@-metadata.jar +source.debezium=https://@repo-spring-io@/org/springframework/cloud/stream/app/debezium-source-kafka/@apps.version@/debezium-source-kafka-@apps.version@.jar +source.debezium.metadata=https://@repo-spring-io@/org/springframework/cloud/stream/app/debezium-source-kafka/@apps.version@/debezium-source-kafka-@apps.version@-metadata.jar source.file=https://@repo-spring-io@/org/springframework/cloud/stream/app/file-source-kafka/@apps.version@/file-source-kafka-@apps.version@.jar source.file.metadata=https://@repo-spring-io@/org/springframework/cloud/stream/app/file-source-kafka/@apps.version@/file-source-kafka-@apps.version@-metadata.jar source.ftp=https://@repo-spring-io@/org/springframework/cloud/stream/app/ftp-source-kafka/@apps.version@/ftp-source-kafka-@apps.version@.jar diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven.properties index 26a268ef..4ba127de 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/kafka-apps-maven.properties @@ -1,5 +1,5 @@ -source.cdc-debezium=maven://org.springframework.cloud.stream.app:cdc-debezium-source-kafka:@apps.version@ -source.cdc-debezium.metadata=maven://org.springframework.cloud.stream.app:cdc-debezium-source-kafka:jar:metadata:@apps.version@ +source.debezium=maven://org.springframework.cloud.stream.app:debezium-source-kafka:@apps.version@ +source.debezium.metadata=maven://org.springframework.cloud.stream.app:debezium-source-kafka:jar:metadata:@apps.version@ source.file=maven://org.springframework.cloud.stream.app:file-source-kafka:@apps.version@ source.file.metadata=maven://org.springframework.cloud.stream.app:file-source-kafka:jar:metadata:@apps.version@ source.ftp=maven://org.springframework.cloud.stream.app:ftp-source-kafka:@apps.version@ diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-docker.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-docker.properties index 6292ee4b..4a53bf60 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-docker.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-docker.properties @@ -1,4 +1,4 @@ -source.cdc-debezium=docker:springcloudstream/cdc-debezium-source-rabbit:@apps.docker.tag@ +source.debezium=docker:springcloudstream/debezium-source-rabbit:@apps.docker.tag@ source.file=docker:springcloudstream/file-source-rabbit:@apps.docker.tag@ source.ftp=docker:springcloudstream/ftp-source-rabbit:@apps.docker.tag@ source.http=docker:springcloudstream/http-source-rabbit:@apps.docker.tag@ diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-harbor.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-harbor.properties index fcb0518e..49af58e4 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-harbor.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-harbor.properties @@ -1,4 +1,4 @@ -source.cdc-debezium=docker:projects.registry.vmware.com/springcloudstream/cdc-debezium-source-rabbit:@apps.harbor.version@ +source.debezium=docker:projects.registry.vmware.com/springcloudstream/debezium-source-rabbit:@apps.harbor.version@ source.file=docker:projects.registry.vmware.com/springcloudstream/file-source-rabbit:@apps.harbor.version@ source.ftp=docker:projects.registry.vmware.com/springcloudstream/ftp-source-rabbit:@apps.harbor.version@ source.http=docker:projects.registry.vmware.com/springcloudstream/http-source-rabbit:@apps.harbor.version@ diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven-repo-url.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven-repo-url.properties index 03265f27..388bdb0f 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven-repo-url.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven-repo-url.properties @@ -1,5 +1,5 @@ -source.cdc-debezium=https://@repo-spring-io@/org/springframework/cloud/stream/app/cdc-debezium-source-rabbit/@apps.version@/cdc-debezium-source-rabbit-@apps.version@.jar -source.cdc-debezium.metadata=https://@repo-spring-io@/org/springframework/cloud/stream/app/cdc-debezium-source-rabbit/@apps.version@/cdc-debezium-source-rabbit-@apps.version@-metadata.jar +source.debezium=https://@repo-spring-io@/org/springframework/cloud/stream/app/debezium-source-rabbit/@apps.version@/debezium-source-rabbit-@apps.version@.jar +source.debezium.metadata=https://@repo-spring-io@/org/springframework/cloud/stream/app/debezium-source-rabbit/@apps.version@/debezium-source-rabbit-@apps.version@-metadata.jar source.file=https://@repo-spring-io@/org/springframework/cloud/stream/app/file-source-rabbit/@apps.version@/file-source-rabbit-@apps.version@.jar source.file.metadata=https://@repo-spring-io@/org/springframework/cloud/stream/app/file-source-rabbit/@apps.version@/file-source-rabbit-@apps.version@-metadata.jar source.ftp=https://@repo-spring-io@/org/springframework/cloud/stream/app/ftp-source-rabbit/@apps.version@/ftp-source-rabbit-@apps.version@.jar diff --git a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven.properties b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven.properties index 80335706..bbcf12ad 100644 --- a/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven.properties +++ b/stream-applications-release-train/stream-applications-descriptor/src/main/resources/META-INF/rabbit-apps-maven.properties @@ -1,5 +1,5 @@ -source.cdc-debezium=maven://org.springframework.cloud.stream.app:cdc-debezium-source-rabbit:@apps.version@ -source.cdc-debezium.metadata=maven://org.springframework.cloud.stream.app:cdc-debezium-source-rabbit:jar:metadata:@apps.version@ +source.debezium=maven://org.springframework.cloud.stream.app:debezium-source-rabbit:@apps.version@ +source.debezium.metadata=maven://org.springframework.cloud.stream.app:debezium-source-rabbit:jar:metadata:@apps.version@ source.file=maven://org.springframework.cloud.stream.app:file-source-rabbit:@apps.version@ source.file.metadata=maven://org.springframework.cloud.stream.app:file-source-rabbit:jar:metadata:@apps.version@ source.ftp=maven://org.springframework.cloud.stream.app:ftp-source-rabbit:@apps.version@ diff --git a/stream-applications-release-train/stream-applications-docs/pom.xml b/stream-applications-release-train/stream-applications-docs/pom.xml index 7bdb374b..b484684a 100644 --- a/stream-applications-release-train/stream-applications-docs/pom.xml +++ b/stream-applications-release-train/stream-applications-docs/pom.xml @@ -26,11 +26,6 @@ Modules with @ConfigurationProperties. --> - - org.springframework.cloud.fn - cdc-debezium-common - ${java-functions.version} - org.springframework.cloud.fn file-common @@ -64,7 +59,7 @@ org.springframework.cloud.fn - cdc-debezium-supplier + debezium-supplier ${java-functions.version} diff --git a/stream-applications-release-train/stream-applications-docs/src/main/asciidoc/sources.adoc b/stream-applications-release-train/stream-applications-docs/src/main/asciidoc/sources.adoc index 312e1672..80e7dc64 100644 --- a/stream-applications-release-train/stream-applications-docs/src/main/asciidoc/sources.adoc +++ b/stream-applications-release-train/stream-applications-docs/src/main/asciidoc/sources.adoc @@ -3,8 +3,8 @@ :leveloffset: +2 -[[spring-cloud-stream-modules-cdc-debezium-source]] -include::{stream-apps-root}/{branch}/applications/source/cdc-debezium-source/README.adoc[tags=ref-doc] +[[spring-cloud-stream-modules-debezium-source]] +include::{stream-apps-root}/{branch}/applications/source/debezium-source/README.adoc[tags=ref-doc] [[spring-cloud-stream-modules-file-source]] include::{stream-apps-root}/{branch}/applications/source/file-source/README.adoc[tags=ref-doc]