Skip to main content

risingwave_connector/source/cdc/enumerator/
mod.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16use std::marker::PhantomData;
17use std::ops::Deref;
18use std::sync::Arc;
19
20use anyhow::{Context, anyhow};
21use async_trait::async_trait;
22use mysql_async::Row;
23use mysql_async::prelude::*;
24use prost::Message;
25use risingwave_common::global_jvm::Jvm;
26use risingwave_common::id::SourceId;
27use risingwave_common::metrics::{LabelGuardedIntGauge, LabelGuardedIntGaugeVec};
28use risingwave_jni_core::call_static_method;
29use risingwave_jni_core::jvm_runtime::execute_with_jni_env;
30use risingwave_pb::connector_service::{SourceType, ValidateSourceRequest, ValidateSourceResponse};
31use tiberius::Config;
32use tokio_postgres::types::PgLsn;
33
34use crate::connector_common::sql_server::MssqlTimeouts;
35use crate::connector_common::{SslMode, create_pg_client, pg_connection_config_from_properties};
36use crate::error::ConnectorResult;
37use crate::sink::sqlserver::SqlServerClient;
38use crate::source::cdc::external::mysql::{
39    build_mariadb_connection_pool, build_mysql_connection_pool,
40};
41use crate::source::cdc::external::sql_server::SqlServerCdcTimeouts;
42use crate::source::cdc::split::{extract_binlog_file_seq, parse_sql_server_lsn_str};
43use crate::source::cdc::{
44    CdcProperties, CdcSourceType, CdcSourceTypeTrait, DebeziumCdcSplit, Mariadb, Mongodb, Mysql,
45    Oracle, Postgres, SqlServer, table_schema_exclude_additional_columns,
46};
47use crate::source::monitor::metrics::EnumeratorMetrics;
48use crate::source::{SourceEnumeratorContextRef, SplitEnumerator};
49
50#[derive(Debug)]
51pub struct DebeziumSplitEnumerator<T: CdcSourceTypeTrait> {
52    /// The `source_id` in the catalog
53    source_id: SourceId,
54    metrics: Arc<EnumeratorMetrics>,
55    pg_cdc_upstream_max_lsn: Option<LabelGuardedIntGauge>,
56    pg_cdc_confirmed_flush_lsn: Option<LabelGuardedIntGauge>,
57    mysql_cdc_binlog_file_seq_min: Option<LabelGuardedIntGauge>,
58    mysql_cdc_binlog_file_seq_max: Option<LabelGuardedIntGauge>,
59    mariadb_cdc_binlog_file_seq_min: Option<LabelGuardedIntGauge>,
60    mariadb_cdc_binlog_file_seq_max: Option<LabelGuardedIntGauge>,
61    sqlserver_cdc_upstream_min_lsn: Option<LabelGuardedIntGauge>,
62    sqlserver_cdc_upstream_max_lsn: Option<LabelGuardedIntGauge>,
63    sqlserver_cdc_timeouts: MssqlTimeouts,
64    /// Properties specified in the WITH clause by user for database connection
65    properties: Arc<BTreeMap<String, String>>,
66    _phantom: PhantomData<T>,
67}
68
69fn get_or_create_guarded_int_gauge<'a>(
70    metric: &'a mut Option<LabelGuardedIntGauge>,
71    metric_vec: &LabelGuardedIntGaugeVec,
72    labels: &[String],
73) -> &'a LabelGuardedIntGauge {
74    metric.get_or_insert_with(|| metric_vec.with_guarded_label_values(labels))
75}
76
77#[async_trait]
78impl<T: CdcSourceTypeTrait> SplitEnumerator for DebeziumSplitEnumerator<T>
79where
80    Self: ListCdcSplits<CdcSourceType = T> + CdcMonitor,
81{
82    type Properties = CdcProperties<T>;
83    type Split = DebeziumCdcSplit<T>;
84
85    async fn new(
86        props: CdcProperties<T>,
87        context: SourceEnumeratorContextRef,
88    ) -> ConnectorResult<Self> {
89        assert_eq!(
90            props.get_source_type_pb(),
91            SourceType::from(T::source_type())
92        );
93
94        let jvm = Jvm::get_or_init()?;
95        let source_id = context.info.source_id;
96
97        // Extract fields before moving props
98        let source_type_pb = props.get_source_type_pb();
99
100        // Create Arc once and share it
101        let properties_arc = Arc::new(props.properties);
102        let sqlserver_cdc_timeouts = match T::source_type() {
103            CdcSourceType::SqlServer => {
104                SqlServerCdcTimeouts::from_properties(&properties_arc)?.timeouts()
105            }
106            _ => MssqlTimeouts::default(),
107        };
108        let properties_arc_for_validation = properties_arc.clone();
109        let table_schema_for_validation = props.table_schema;
110
111        tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
112            execute_with_jni_env(jvm, |env| {
113                let validate_source_request = ValidateSourceRequest {
114                    source_id: source_id.as_raw_id() as u64,
115                    source_type: source_type_pb as _,
116                    properties: (*properties_arc_for_validation).clone(),
117                    table_schema: Some(table_schema_exclude_additional_columns(
118                        &table_schema_for_validation,
119                    )),
120                    is_source_job: props.is_cdc_source_job,
121                    is_backfill_table: props.is_backfill_table,
122                };
123
124                let validate_source_request_bytes =
125                    env.byte_array_from_slice(&Message::encode_to_vec(&validate_source_request))?;
126
127                let validate_source_response_bytes = call_static_method!(
128                    env,
129                    {com.risingwave.connector.source.JniSourceValidateHandler},
130                    {byte[] validate(byte[] validateSourceRequestBytes)},
131                    &validate_source_request_bytes
132                )?;
133
134                let validate_source_response: ValidateSourceResponse = Message::decode(
135                    risingwave_jni_core::to_guarded_slice(&validate_source_response_bytes, env)?
136                        .deref(),
137                )?;
138
139                if let Some(error) = validate_source_response.error {
140                    return Err(anyhow!(error.error_message).context("source validation failed"));
141                }
142
143                Ok(())
144            })
145        })
146        .await
147        .context("failed to validate source")??;
148
149        tracing::debug!("validate cdc source properties success");
150        Ok(Self {
151            source_id,
152            metrics: context.metrics.clone(),
153            pg_cdc_upstream_max_lsn: None,
154            pg_cdc_confirmed_flush_lsn: None,
155            mysql_cdc_binlog_file_seq_min: None,
156            mysql_cdc_binlog_file_seq_max: None,
157            mariadb_cdc_binlog_file_seq_min: None,
158            mariadb_cdc_binlog_file_seq_max: None,
159            sqlserver_cdc_upstream_min_lsn: None,
160            sqlserver_cdc_upstream_max_lsn: None,
161            sqlserver_cdc_timeouts,
162            properties: properties_arc,
163            _phantom: PhantomData,
164        })
165    }
166
167    async fn list_splits(&mut self) -> ConnectorResult<Vec<DebeziumCdcSplit<T>>> {
168        Ok(self.list_cdc_splits())
169    }
170
171    async fn on_tick(&mut self) -> ConnectorResult<()> {
172        self.monitor_cdc().await
173    }
174}
175
176impl<T: CdcSourceTypeTrait> DebeziumSplitEnumerator<T> {
177    fn sql_server_lsn_to_i64(lsn: &str) -> Option<i64> {
178        parse_sql_server_lsn_str(lsn).map(|v| v.min(i64::MAX as u128) as i64)
179    }
180
181    fn pg_cdc_lsn_metric_labels(&self, slot_name: &str) -> Vec<String> {
182        vec![self.source_id.to_string(), slot_name.to_owned()]
183    }
184
185    async fn monitor_postgres_confirmed_flush_lsn(&mut self) -> ConnectorResult<()> {
186        // Query upstream LSNs and update metrics.
187        let lsns = self.query_postgres_lsns().await.with_context(|| {
188            format!(
189                "failed to query PostgreSQL LSNs for source {}",
190                self.source_id
191            )
192        })?;
193        match lsns {
194            Some((confirmed_flush_lsn, upstream_max_lsn, slot_name)) => {
195                let labels = self.pg_cdc_lsn_metric_labels(&slot_name);
196
197                get_or_create_guarded_int_gauge(
198                    &mut self.pg_cdc_upstream_max_lsn,
199                    &self.metrics.pg_cdc_upstream_max_lsn,
200                    &labels,
201                )
202                .set(upstream_max_lsn as i64);
203
204                if let Some(lsn) = confirmed_flush_lsn {
205                    get_or_create_guarded_int_gauge(
206                        &mut self.pg_cdc_confirmed_flush_lsn,
207                        &self.metrics.pg_cdc_confirmed_flush_lsn,
208                        &labels,
209                    )
210                    .set(lsn as i64);
211                    tracing::debug!(
212                        "Updated confirmed_flush_lsn for source {} slot {}: {}",
213                        self.source_id,
214                        slot_name,
215                        lsn
216                    );
217                } else {
218                    tracing::warn!(
219                        "confirmed_flush_lsn is NULL for source {} slot {}",
220                        self.source_id,
221                        slot_name
222                    );
223                }
224            }
225            None => {
226                tracing::warn!(
227                    "no replication slot was found while querying LSNs for source {}",
228                    self.source_id
229                );
230            }
231        };
232        Ok(())
233    }
234
235    /// Query LSNs from PostgreSQL, return (`confirmed_flush_lsn`, `upstream_max_lsn`, `slot_name`).
236    async fn query_postgres_lsns(&self) -> ConnectorResult<Option<(Option<u64>, u64, String)>> {
237        let pg_conn = pg_connection_config_from_properties(&self.properties)?;
238
239        let slot_name = self
240            .properties
241            .get("slot.name")
242            .ok_or_else(|| anyhow::anyhow!("missing `slot.name` in CDC properties"))?;
243
244        // No TCP keepalive for CDC enumerator
245        let application_name = format!("risingwave-postgres-source-enumerator-{}", self.source_id);
246        let client = create_pg_client(&pg_conn, None, Some(&application_name))
247            .await
248            .context("failed to create the PostgreSQL client")?;
249
250        let query = "SELECT confirmed_flush_lsn, pg_current_wal_lsn() \
251            FROM pg_replication_slots WHERE slot_name = $1";
252        let row = client
253            .query_opt(query, &[&slot_name])
254            .await
255            .context("failed to query PostgreSQL LSNs")?;
256        match row {
257            Some(row) => {
258                let confirmed_flush_lsn: Option<PgLsn> = row.get(0);
259                let upstream_max_lsn: PgLsn = row.get(1);
260                Ok(Some((
261                    confirmed_flush_lsn.map(Into::into),
262                    upstream_max_lsn.into(),
263                    slot_name.clone(),
264                )))
265            }
266            None => {
267                tracing::warn!("no replication slot found with name: {}", slot_name);
268                Ok(None)
269            }
270        }
271    }
272
273    /// Query min/max LSNs from SQL Server CDC.
274    async fn query_sql_server_lsns(&self) -> ConnectorResult<Option<(String, String)>> {
275        let hostname = self
276            .properties
277            .get("hostname")
278            .ok_or_else(|| anyhow!("missing `hostname` in CDC properties"))?;
279        let port = self
280            .properties
281            .get("port")
282            .ok_or_else(|| anyhow!("missing `port` in CDC properties"))?
283            .parse::<u16>()
284            .context("failed to parse `port` as a u16")?;
285        let username = self
286            .properties
287            .get("username")
288            .ok_or_else(|| anyhow!("missing `username` in CDC properties"))?;
289        let password = self
290            .properties
291            .get("password")
292            .ok_or_else(|| anyhow!("missing `password` in CDC properties"))?;
293        let database = self
294            .properties
295            .get("database.name")
296            .ok_or_else(|| anyhow!("missing `database.name` in CDC properties"))?;
297
298        let mut config = Config::new();
299        config.host(hostname);
300        config.port(port);
301        config.database(database);
302        config.authentication(tiberius::AuthMethod::sql_server(username, password));
303        config.trust_cert();
304
305        let mut client =
306            SqlServerClient::new_with_config(config, self.sqlserver_cdc_timeouts).await?;
307        let row = client
308            .inner_client
309            .simple_query(
310                "SELECT \
311                    sys.fn_cdc_get_max_lsn() AS max_lsn, \
312                    (SELECT MIN(sys.fn_cdc_get_min_lsn(capture_instance)) FROM cdc.change_tables) AS min_lsn"
313                    .to_owned(),
314            )
315            .await?
316            .into_row()
317            .await?
318            .ok_or_else(|| anyhow!("No result returned when querying SQL Server max/min LSN"))?;
319
320        let lsn_bytes_to_hex = |bytes: &[u8]| -> ConnectorResult<String> {
321            if bytes.len() != 10 {
322                return Err(anyhow!(
323                    "SQL Server LSN should be 10 bytes, got {} bytes",
324                    bytes.len()
325                )
326                .into());
327            }
328            let mut hex_string = String::with_capacity(22);
329            for byte in &bytes[0..4] {
330                hex_string.push_str(&format!("{:02x}", byte));
331            }
332            hex_string.push(':');
333            for byte in &bytes[4..8] {
334                hex_string.push_str(&format!("{:02x}", byte));
335            }
336            hex_string.push(':');
337            for byte in &bytes[8..10] {
338                hex_string.push_str(&format!("{:02x}", byte));
339            }
340            Ok(hex_string)
341        };
342
343        let max_lsn = row
344            .try_get::<&[u8], usize>(0)?
345            .map(lsn_bytes_to_hex)
346            .transpose()?
347            .ok_or_else(|| anyhow!("SQL Server max_lsn is NULL"))?;
348        let min_lsn = row
349            .try_get::<&[u8], usize>(1)?
350            .map(lsn_bytes_to_hex)
351            .transpose()?
352            .ok_or_else(|| anyhow!("SQL Server min_lsn is NULL"))?;
353
354        Ok(Some((min_lsn, max_lsn)))
355    }
356
357    async fn monitor_sql_server_lsns(&mut self) -> ConnectorResult<()> {
358        let lsns = self.query_sql_server_lsns().await.with_context(|| {
359            format!(
360                "failed to query SQL Server LSNs for source {}",
361                self.source_id
362            )
363        })?;
364        if let Some((min_lsn, max_lsn)) = lsns {
365            let labels = vec![self.source_id.to_string()];
366
367            if let Some(value) = Self::sql_server_lsn_to_i64(&min_lsn) {
368                get_or_create_guarded_int_gauge(
369                    &mut self.sqlserver_cdc_upstream_min_lsn,
370                    &self.metrics.sqlserver_cdc_upstream_min_lsn,
371                    &labels,
372                )
373                .set(value);
374            }
375            if let Some(value) = Self::sql_server_lsn_to_i64(&max_lsn) {
376                get_or_create_guarded_int_gauge(
377                    &mut self.sqlserver_cdc_upstream_max_lsn,
378                    &self.metrics.sqlserver_cdc_upstream_max_lsn,
379                    &labels,
380                )
381                .set(value);
382            }
383        }
384
385        Ok(())
386    }
387}
388
389pub trait ListCdcSplits {
390    type CdcSourceType: CdcSourceTypeTrait;
391    /// Generates a single split for shared source.
392    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>>;
393}
394
395/// Trait for CDC-specific monitoring behavior
396#[async_trait]
397pub trait CdcMonitor {
398    async fn monitor_cdc(&mut self) -> ConnectorResult<()>;
399}
400
401#[async_trait]
402impl<T: CdcSourceTypeTrait> CdcMonitor for DebeziumSplitEnumerator<T> {
403    default async fn monitor_cdc(&mut self) -> ConnectorResult<()> {
404        Ok(())
405    }
406}
407
408impl DebeziumSplitEnumerator<Mysql> {
409    async fn monitor_mysql_binlog_files(&mut self) -> ConnectorResult<()> {
410        // Get hostname and port for metrics labels
411        let hostname = self
412            .properties
413            .get("hostname")
414            .map(|s| s.as_str())
415            .ok_or_else(|| {
416                anyhow::anyhow!("missing required property 'hostname' for MySQL CDC source")
417            })?;
418        let port = self
419            .properties
420            .get("port")
421            .map(|s| s.as_str())
422            .ok_or_else(|| {
423                anyhow::anyhow!("missing required property 'port' for MySQL CDC source")
424            })?;
425
426        // Query binlog files and update metrics
427        let binlog_files = self.query_binlog_files().await.with_context(|| {
428            format!(
429                "failed to query binlog files for MySQL CDC source {} ({}:{})",
430                self.source_id, hostname, port
431            )
432        })?;
433        if let Some((oldest_file, oldest_size)) = binlog_files.first()
434            && let Some(seq) = extract_binlog_file_seq(oldest_file)
435        {
436            let labels = vec![
437                self.source_id.to_string(),
438                hostname.to_owned(),
439                port.to_owned(),
440            ];
441            get_or_create_guarded_int_gauge(
442                &mut self.mysql_cdc_binlog_file_seq_min,
443                &self.metrics.mysql_cdc_binlog_file_seq_min,
444                &labels,
445            )
446            .set(seq as i64);
447            tracing::debug!(
448                "MySQL CDC source {} ({}:{}): oldest binlog = {}, seq = {}, size = {}",
449                self.source_id,
450                hostname,
451                port,
452                oldest_file,
453                seq,
454                oldest_size
455            );
456        }
457        if let Some((newest_file, newest_size)) = binlog_files.last()
458            && let Some(seq) = extract_binlog_file_seq(newest_file)
459        {
460            let labels = vec![
461                self.source_id.to_string(),
462                hostname.to_owned(),
463                port.to_owned(),
464            ];
465            get_or_create_guarded_int_gauge(
466                &mut self.mysql_cdc_binlog_file_seq_max,
467                &self.metrics.mysql_cdc_binlog_file_seq_max,
468                &labels,
469            )
470            .set(seq as i64);
471            tracing::debug!(
472                "MySQL CDC source {} ({}:{}): newest binlog = {}, seq = {}, size = {}",
473                self.source_id,
474                hostname,
475                port,
476                newest_file,
477                seq,
478                newest_size
479            );
480        }
481        tracing::debug!(
482            "MySQL CDC source {} ({}:{}): total {} binlog files",
483            self.source_id,
484            hostname,
485            port,
486            binlog_files.len()
487        );
488        Ok(())
489    }
490
491    /// Query binlog files from MySQL, returns Vec<(filename, size)>
492    async fn query_binlog_files(&self) -> ConnectorResult<Vec<(String, u64)>> {
493        // Extract connection parameters from CDC properties
494        let hostname = self
495            .properties
496            .get("hostname")
497            .ok_or_else(|| anyhow::anyhow!("missing `hostname` in CDC properties"))?;
498        let port = self
499            .properties
500            .get("port")
501            .ok_or_else(|| anyhow::anyhow!("missing `port` in CDC properties"))?
502            .parse::<u16>()
503            .context("failed to parse `port` as a u16")?;
504        let username = self
505            .properties
506            .get("username")
507            .ok_or_else(|| anyhow::anyhow!("missing `username` in CDC properties"))?;
508        let password = self
509            .properties
510            .get("password")
511            .ok_or_else(|| anyhow::anyhow!("missing `password` in CDC properties"))?;
512        // Get SSL mode configuration (default to Disabled if not specified)
513        let ssl_mode = self
514            .properties
515            .get("ssl.mode")
516            .and_then(|s| s.parse().ok())
517            .unwrap_or(SslMode::Preferred);
518
519        // SHOW BINARY LOGS is server-wide. Do not select a default database: database.name
520        // can be a comma-separated list for a shared source.
521        let pool = build_mysql_connection_pool(hostname, port, username, password, None, ssl_mode);
522        let mut conn = pool
523            .get_conn()
524            .await
525            .context("failed to connect to MySQL")?;
526
527        // Query binlog files using SHOW BINARY LOGS.
528        // MySQL 8.0+ may return 3 columns (Log_name, File_size, Encrypted), while some variants
529        // only return the first 2. Decode the row manually so we don't panic on column-count
530        // differences.
531        let rows: Vec<Row> = conn
532            .query("SHOW BINARY LOGS")
533            .await
534            .context("failed to execute `SHOW BINARY LOGS`")?;
535        let query_result = rows
536            .into_iter()
537            .map(|mut row| -> ConnectorResult<(String, u64)> {
538                let log_name = row
539                    .take_opt::<String, _>(0)
540                    .transpose()
541                    .context("`SHOW BINARY LOGS`: failed to decode `Log_name`")?
542                    .ok_or_else(|| anyhow!("`SHOW BINARY LOGS`: missing `Log_name` column"))?;
543                let file_size = row
544                    .take_opt::<u64, _>(1)
545                    .transpose()
546                    .context("`SHOW BINARY LOGS`: failed to decode `File_size`")?
547                    .ok_or_else(|| anyhow!("`SHOW BINARY LOGS`: missing `File_size` column"))?;
548                Ok((log_name, file_size))
549            })
550            .collect::<ConnectorResult<Vec<_>>>()?;
551
552        drop(conn);
553        pool.disconnect().await.ok();
554
555        Ok(query_result)
556    }
557}
558
559impl ListCdcSplits for DebeziumSplitEnumerator<Mysql> {
560    type CdcSourceType = Mysql;
561
562    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>> {
563        // CDC source only supports single split
564        vec![DebeziumCdcSplit::<Self::CdcSourceType>::new(
565            self.source_id.as_raw_id(),
566            None,
567        )]
568    }
569}
570
571impl ListCdcSplits for DebeziumSplitEnumerator<Mariadb> {
572    type CdcSourceType = Mariadb;
573
574    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>> {
575        vec![DebeziumCdcSplit::<Self::CdcSourceType>::new(
576            self.source_id.as_raw_id(),
577            None,
578        )]
579    }
580}
581
582impl DebeziumSplitEnumerator<Mariadb> {
583    async fn monitor_mariadb_binlog_files(&mut self) -> ConnectorResult<()> {
584        let hostname = self.properties.get("hostname").ok_or_else(|| {
585            anyhow!("missing required property 'hostname' for MariaDB CDC source")
586        })?;
587        let port = self
588            .properties
589            .get("port")
590            .ok_or_else(|| anyhow!("missing required property 'port' for MariaDB CDC source"))?;
591        let binlog_files = query_mariadb_binlog_files(&self.properties)
592            .await
593            .with_context(|| {
594                format!(
595                    "failed to query binlog files for MariaDB CDC source {} ({}:{})",
596                    self.source_id, hostname, port
597                )
598            })?;
599        let labels = vec![
600            self.source_id.to_string(),
601            hostname.to_owned(),
602            port.to_owned(),
603        ];
604        if let Some((oldest_file, _)) = binlog_files.first()
605            && let Some(seq) = extract_binlog_file_seq(oldest_file)
606        {
607            get_or_create_guarded_int_gauge(
608                &mut self.mariadb_cdc_binlog_file_seq_min,
609                &self.metrics.mariadb_cdc_binlog_file_seq_min,
610                &labels,
611            )
612            .set(seq as i64);
613        }
614        if let Some((newest_file, _)) = binlog_files.last()
615            && let Some(seq) = extract_binlog_file_seq(newest_file)
616        {
617            get_or_create_guarded_int_gauge(
618                &mut self.mariadb_cdc_binlog_file_seq_max,
619                &self.metrics.mariadb_cdc_binlog_file_seq_max,
620                &labels,
621            )
622            .set(seq as i64);
623        }
624        Ok(())
625    }
626}
627
628async fn query_mariadb_binlog_files(
629    properties: &BTreeMap<String, String>,
630) -> ConnectorResult<Vec<(String, u64)>> {
631    let hostname = properties
632        .get("hostname")
633        .ok_or_else(|| anyhow!("missing `hostname` in CDC properties"))?;
634    let port = properties
635        .get("port")
636        .ok_or_else(|| anyhow!("missing `port` in CDC properties"))?
637        .parse::<u16>()
638        .context("failed to parse `port` as a u16")?;
639    let username = properties
640        .get("username")
641        .ok_or_else(|| anyhow!("missing `username` in CDC properties"))?;
642    let password = properties
643        .get("password")
644        .ok_or_else(|| anyhow!("missing `password` in CDC properties"))?;
645    let ssl_mode = properties
646        .get("ssl.mode")
647        .or_else(|| properties.get("debezium.database.sslmode"))
648        .and_then(|s| s.parse().ok())
649        .unwrap_or(SslMode::Preferred);
650    let ssl_root_cert = properties
651        .get("ssl.root.cert")
652        .or_else(|| properties.get("debezium.database.sslrootcert"))
653        .map(String::as_str);
654    // SHOW BINARY LOGS is server-wide. `database.name` can contain multiple databases.
655    let pool = build_mariadb_connection_pool(
656        hostname,
657        port,
658        username,
659        password,
660        None,
661        ssl_mode,
662        ssl_root_cert,
663    );
664    let mut conn = pool
665        .get_conn()
666        .await
667        .context("failed to connect to MariaDB")?;
668    let rows: Vec<Row> = conn
669        .query("SHOW BINARY LOGS")
670        .await
671        .context("failed to execute `SHOW BINARY LOGS`")?;
672    let result = rows
673        .into_iter()
674        .map(|mut row| -> ConnectorResult<(String, u64)> {
675            let name = row
676                .take_opt::<String, _>(0)
677                .transpose()
678                .context("failed to decode MariaDB binlog name")?
679                .ok_or_else(|| anyhow!("missing MariaDB binlog name"))?;
680            let size = row
681                .take_opt::<u64, _>(1)
682                .transpose()
683                .context("failed to decode MariaDB binlog size")?
684                .ok_or_else(|| anyhow!("missing MariaDB binlog size"))?;
685            Ok((name, size))
686        })
687        .collect::<ConnectorResult<Vec<_>>>()?;
688    drop(conn);
689    pool.disconnect().await.ok();
690    Ok(result)
691}
692
693#[async_trait]
694impl CdcMonitor for DebeziumSplitEnumerator<Mariadb> {
695    async fn monitor_cdc(&mut self) -> ConnectorResult<()> {
696        self.monitor_mariadb_binlog_files().await
697    }
698}
699
700#[async_trait]
701impl CdcMonitor for DebeziumSplitEnumerator<Mysql> {
702    async fn monitor_cdc(&mut self) -> ConnectorResult<()> {
703        // For MySQL CDC, query the upstream MySQL binlog files and monitor them.
704        self.monitor_mysql_binlog_files().await?;
705        Ok(())
706    }
707}
708
709impl ListCdcSplits for DebeziumSplitEnumerator<Postgres> {
710    type CdcSourceType = Postgres;
711
712    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>> {
713        // CDC source only supports single split
714        vec![DebeziumCdcSplit::<Self::CdcSourceType>::new(
715            self.source_id.as_raw_id(),
716            None,
717        )]
718    }
719}
720
721#[async_trait]
722impl CdcMonitor for DebeziumSplitEnumerator<Postgres> {
723    async fn monitor_cdc(&mut self) -> ConnectorResult<()> {
724        // For PostgreSQL CDC, query the upstream Postgres confirmed flush lsn and monitor it.
725        self.monitor_postgres_confirmed_flush_lsn().await?;
726        Ok(())
727    }
728}
729
730impl ListCdcSplits for DebeziumSplitEnumerator<Mongodb> {
731    type CdcSourceType = Mongodb;
732
733    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>> {
734        // CDC source only supports single split
735        vec![DebeziumCdcSplit::<Self::CdcSourceType>::new(
736            self.source_id.as_raw_id(),
737            None,
738        )]
739    }
740}
741
742impl ListCdcSplits for DebeziumSplitEnumerator<SqlServer> {
743    type CdcSourceType = SqlServer;
744
745    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>> {
746        vec![DebeziumCdcSplit::<Self::CdcSourceType>::new(
747            self.source_id.as_raw_id(),
748            None,
749        )]
750    }
751}
752
753impl ListCdcSplits for DebeziumSplitEnumerator<Oracle> {
754    type CdcSourceType = Oracle;
755
756    fn list_cdc_splits(&mut self) -> Vec<DebeziumCdcSplit<Self::CdcSourceType>> {
757        vec![DebeziumCdcSplit::<Self::CdcSourceType>::new(
758            self.source_id.as_raw_id(),
759            None,
760        )]
761    }
762}
763
764#[async_trait]
765impl CdcMonitor for DebeziumSplitEnumerator<SqlServer> {
766    async fn monitor_cdc(&mut self) -> ConnectorResult<()> {
767        self.monitor_sql_server_lsns().await
768    }
769}
770
771#[cfg(test)]
772mod tests {
773    use prometheus::core::Collector;
774    use risingwave_common::metrics::LabelGuardedIntGaugeVec;
775
776    use super::get_or_create_guarded_int_gauge;
777
778    #[test]
779    fn cached_guarded_metric_survives_repeated_collections() {
780        let metric_vec = LabelGuardedIntGaugeVec::test_int_gauge_vec::<2>();
781        let labels = vec!["source_id".to_owned(), "slot_name".to_owned()];
782        let mut metric = None;
783
784        get_or_create_guarded_int_gauge(&mut metric, &metric_vec, &labels).set(1);
785
786        assert_eq!(1, metric_vec.collect().pop().unwrap().get_metric().len());
787        assert_eq!(1, metric_vec.collect().pop().unwrap().get_metric().len());
788
789        drop(metric);
790        assert_eq!(1, metric_vec.collect().pop().unwrap().get_metric().len());
791        assert_eq!(0, metric_vec.collect().pop().unwrap().get_metric().len());
792    }
793}