Skip to main content

mz_storage/source/
mysql.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Code to render the ingestion dataflow of a [`MySqlSourceConnection`].
11//!
12//! This dataflow is split into Snapshot and Replication operators.
13//!
14//! # Snapshot
15//!
16//! The snapshot operator is responsible for taking a consistent snapshot of the tables involved
17//! in the ingestion from the MySQL server. Each table that is being ingested is snapshot is
18//! assigned a specific worker, which performs a `SELECT * FROM table` and emits updates for all
19//! the rows in the given table.
20//!
21//! For all tables that are snapshotted the snapshot operator also emits a rewind request to
22//! the replication operator containing the GTID-set based frontier which will be used to
23//! ensure that the requested portion of the replication stream is subtracted from the snapshot.
24//!
25//! See the [snapshot] module for more information.
26//!
27//! # Replication
28//!
29//! The replication operator is responsible for ingesting the MySQL replication stream which must
30//! happen from a single worker.
31//!
32//! See the [replication] module for more information.
33//!
34//! # Error handling
35//!
36//! There are two kinds of errors that can happen during ingestion that are represented as two
37//! separate error types:
38//!
39//! [`DefiniteError`]s are errors that happen during processing of a specific collection record.
40//! These are the only errors that can ever end up in the error collection of a subsource.
41//!
42//! [`TransientError`]s are any errors that can happen for reasons that are unrelated to the data
43//! itself. This could be authentication failures, connection failures, etc. The only operators
44//! that can emit such errors are the `MySqlReplicationReader` and the `MySqlSnapshotReader`
45//! operators, which are the ones that talk to the external world. Both of these operators are
46//! built with the `AsyncOperatorBuilder::build_fallible` method which allows transient errors
47//! to be propagated upwards with the standard `?` operator without risking downgrading the
48//! capability and producing bogus frontiers.
49//!
50//! The error streams from both of those operators are published to the source status and also
51//! trigger a restart of the dataflow.
52
53use std::collections::BTreeMap;
54use std::fmt;
55use std::io;
56use std::rc::Rc;
57
58use differential_dataflow::AsCollection;
59use differential_dataflow::containers::TimelyStack;
60use itertools::Itertools;
61use mz_mysql_util::quote_identifier;
62use mz_ore::cast::CastFrom;
63use mz_repr::Diff;
64use mz_repr::GlobalId;
65use mz_storage_types::errors::{DataflowError, SourceError};
66use mz_storage_types::sources::SourceExport;
67use mz_timely_util::containers::stack::AccountedStackBuilder;
68use serde::{Deserialize, Serialize};
69use timely::container::CapacityContainerBuilder;
70use timely::dataflow::operators::core::Partition;
71use timely::dataflow::operators::vec::{Map, ToStream};
72use timely::dataflow::operators::{CapabilitySet, Concat};
73use timely::dataflow::{Scope, StreamVec};
74use timely::progress::Antichain;
75use uuid::Uuid;
76
77use mz_mysql_util::{
78    MySqlError, MySqlTableDesc, ensure_full_row_binlog_format, ensure_gtid_consistency,
79    ensure_replication_commit_order,
80};
81use mz_ore::error::ErrorExt;
82use mz_storage_types::errors::SourceErrorDetails;
83use mz_storage_types::sources::mysql::{GtidPartition, GtidState, gtid_set_frontier};
84use mz_storage_types::sources::{MySqlSourceConnection, SourceExportDetails, SourceTimestamp};
85use mz_timely_util::builder_async::{AsyncOutputHandle, PressOnDropButton};
86use mz_timely_util::order::Extrema;
87
88use crate::healthcheck::{HealthStatusMessage, HealthStatusUpdate, StatusNamespace};
89use crate::source::types::Probe;
90use crate::source::types::{SourceRender, StackedCollection};
91use crate::source::{RawSourceCreationConfig, SourceMessage};
92
93mod replication;
94mod schemas;
95mod snapshot;
96mod statistics;
97
98impl SourceRender for MySqlSourceConnection {
99    type Time = GtidPartition;
100
101    const STATUS_NAMESPACE: StatusNamespace = StatusNamespace::MySql;
102
103    /// Render the ingestion dataflow. This function only connects things together and contains no
104    /// actual processing logic.
105    fn render<G: Scope<Timestamp = GtidPartition>>(
106        self,
107        scope: &mut G,
108        config: &RawSourceCreationConfig,
109        resume_uppers: impl futures::Stream<Item = Antichain<GtidPartition>> + 'static,
110        _start_signal: impl std::future::Future<Output = ()> + 'static,
111    ) -> (
112        BTreeMap<GlobalId, StackedCollection<G, Result<SourceMessage, DataflowError>>>,
113        StreamVec<G, HealthStatusMessage>,
114        StreamVec<G, Probe<GtidPartition>>,
115        Vec<PressOnDropButton>,
116    ) {
117        // Collect the source outputs that we will be exporting.
118        let mut source_outputs = Vec::new();
119        for (idx, (id, export)) in config.source_exports.iter().enumerate() {
120            let SourceExport {
121                details,
122                storage_metadata: _,
123                data_config: _,
124            } = export;
125            let details = match details {
126                SourceExportDetails::MySql(details) => details,
127                // This is an export that doesn't need any data output to it.
128                SourceExportDetails::None => continue,
129                _ => panic!("unexpected source export details: {:?}", details),
130            };
131
132            let desc = details.table.clone();
133            let initial_gtid_set = details.initial_gtid_set.to_string();
134            let resume_upper = Antichain::from_iter(
135                config
136                    .source_resume_uppers
137                    .get(id)
138                    .expect("missing resume upper")
139                    .iter()
140                    .map(GtidPartition::decode_row),
141            );
142            let name = MySqlTableName::new(&desc.schema_name, &desc.name);
143            source_outputs.push(SourceOutputInfo {
144                output_index: idx,
145                table_name: name.clone(),
146                desc,
147                text_columns: details.text_columns.clone(),
148                exclude_columns: details.exclude_columns.clone(),
149                initial_gtid_set: gtid_set_frontier(&initial_gtid_set).expect("invalid gtid set"),
150                resume_upper,
151                export_id: id.clone(),
152            });
153        }
154
155        let metrics = config.metrics.get_mysql_source_metrics(config.id);
156
157        let (snapshot_updates, rewinds, snapshot_err, snapshot_token) = snapshot::render(
158            scope.clone(),
159            config.clone(),
160            self.clone(),
161            source_outputs.clone(),
162            metrics.snapshot_metrics.clone(),
163        );
164
165        let (repl_updates, repl_err, repl_token) = replication::render(
166            scope.clone(),
167            config.clone(),
168            self.clone(),
169            source_outputs,
170            rewinds,
171            metrics,
172        );
173
174        let (stats_err, probe_stream, stats_token) =
175            statistics::render(scope.clone(), config.clone(), self, resume_uppers);
176
177        let updates = snapshot_updates.concat(repl_updates);
178        let partition_count = u64::cast_from(config.source_exports.len());
179        let data_streams: Vec<_> = updates
180            .inner
181            .partition::<CapacityContainerBuilder<_>, _, _>(
182                partition_count,
183                |((output, data), time, diff): &(
184                    (usize, Result<SourceMessage, DataflowError>),
185                    _,
186                    Diff,
187                )| {
188                    let output = u64::cast_from(*output);
189                    (output, (data.clone(), time.clone(), diff.clone()))
190                },
191            );
192        let mut data_collections = BTreeMap::new();
193        for (id, data_stream) in config.source_exports.keys().zip_eq(data_streams) {
194            data_collections.insert(*id, data_stream.as_collection());
195        }
196
197        let export_ids = config.source_exports.keys().copied();
198        let health_init = export_ids
199            .map(Some)
200            .chain(std::iter::once(None))
201            .map(|id| HealthStatusMessage {
202                id,
203                namespace: Self::STATUS_NAMESPACE,
204                update: HealthStatusUpdate::Running,
205            })
206            .collect::<Vec<_>>()
207            .to_stream(scope);
208
209        let health_errs = snapshot_err
210            .concat(repl_err)
211            .concat(stats_err)
212            .map(move |err| {
213                // This update will cause the dataflow to restart
214                let err_string = err.display_with_causes().to_string();
215                let update = HealthStatusUpdate::halting(err_string.clone(), None);
216
217                let namespace = match err {
218                    ReplicationError::Transient(err)
219                        if matches!(&*err, TransientError::MySqlError(MySqlError::Ssh(_))) =>
220                    {
221                        StatusNamespace::Ssh
222                    }
223                    _ => Self::STATUS_NAMESPACE,
224                };
225
226                HealthStatusMessage {
227                    id: None,
228                    namespace: namespace.clone(),
229                    update,
230                }
231            });
232        let health = health_init.concat(health_errs);
233
234        (
235            data_collections,
236            health,
237            probe_stream,
238            vec![snapshot_token, repl_token, stats_token],
239        )
240    }
241}
242
243#[derive(Clone, Debug)]
244struct SourceOutputInfo {
245    output_index: usize,
246    table_name: MySqlTableName,
247    desc: MySqlTableDesc,
248    text_columns: Vec<String>,
249    exclude_columns: Vec<String>,
250    initial_gtid_set: Antichain<GtidPartition>,
251    resume_upper: Antichain<GtidPartition>,
252    export_id: GlobalId,
253}
254
255#[derive(Clone, Debug, thiserror::Error)]
256pub enum ReplicationError {
257    #[error(transparent)]
258    Transient(#[from] Rc<TransientError>),
259    #[error(transparent)]
260    Definite(#[from] Rc<DefiniteError>),
261}
262
263/// A transient error that never ends up in the collection of a specific table.
264#[derive(Debug, thiserror::Error)]
265pub enum TransientError {
266    #[error("couldn't decode binlog row")]
267    BinlogRowDecodeError(#[from] mysql_async::binlog::row::BinlogRowToRowError),
268    #[error("stream ended prematurely")]
269    ReplicationEOF,
270    #[error(transparent)]
271    IoError(#[from] io::Error),
272    #[error("sql client error")]
273    SQLClient(#[from] mysql_async::Error),
274    #[error("ident decode error")]
275    IdentError(#[from] mz_sql_parser::ast::IdentError),
276    #[error(transparent)]
277    MySqlError(#[from] MySqlError),
278    #[error(transparent)]
279    Generic(#[from] anyhow::Error),
280}
281
282/// A definite error that always ends up in the collection of a specific table.
283#[derive(Debug, Clone, Serialize, Deserialize, thiserror::Error)]
284pub enum DefiniteError {
285    #[error("unable to decode: {0}")]
286    ValueDecodeError(String),
287    #[error("table was truncated: {0}")]
288    TableTruncated(String),
289    #[error("table was dropped: {0}")]
290    TableDropped(String),
291    #[error("incompatible schema change: {0}")]
292    IncompatibleSchema(String),
293    #[error("received a gtid set from the server that violates our requirements: {0}")]
294    UnsupportedGtidState(String),
295    #[error("received out of order gtids for source {0} at transaction-id {1}")]
296    BinlogGtidMonotonicityViolation(String, GtidState),
297    #[error("mysql server does not have the binlog available at the requested gtid set")]
298    BinlogNotAvailable,
299    #[error("mysql server binlog frontier at {0} is beyond required frontier {1}")]
300    BinlogMissingResumePoint(String, String),
301    #[error("mysql server configuration: {0}")]
302    ServerConfigurationError(String),
303}
304
305impl From<DefiniteError> for DataflowError {
306    fn from(err: DefiniteError) -> Self {
307        let m = err.to_string().into();
308        DataflowError::SourceError(Box::new(SourceError {
309            error: match &err {
310                DefiniteError::ValueDecodeError(_) => SourceErrorDetails::Other(m),
311                DefiniteError::TableTruncated(_) => SourceErrorDetails::Other(m),
312                DefiniteError::TableDropped(_) => SourceErrorDetails::Other(m),
313                DefiniteError::IncompatibleSchema(_) => SourceErrorDetails::Other(m),
314                DefiniteError::UnsupportedGtidState(_) => SourceErrorDetails::Other(m),
315                DefiniteError::BinlogGtidMonotonicityViolation(_, _) => {
316                    SourceErrorDetails::Other(m)
317                }
318                DefiniteError::BinlogNotAvailable => SourceErrorDetails::Initialization(m),
319                DefiniteError::BinlogMissingResumePoint(_, _) => {
320                    SourceErrorDetails::Initialization(m)
321                }
322                DefiniteError::ServerConfigurationError(_) => SourceErrorDetails::Initialization(m),
323            },
324        }))
325    }
326}
327
328/// A reference to a MySQL table. (schema_name, table_name)
329/// NOTE: We do not use `mz_sql_parser::ast:UnresolvedItemName` because the serialization
330/// behavior is not what we need for mysql.
331#[derive(
332    Debug,
333    Clone,
334    PartialEq,
335    Eq,
336    PartialOrd,
337    Ord,
338    Serialize,
339    Deserialize,
340    Hash
341)]
342pub(crate) struct MySqlTableName(pub(crate) String, pub(crate) String);
343
344impl MySqlTableName {
345    pub(crate) fn new(schema_name: &str, table_name: &str) -> Self {
346        Self(schema_name.to_string(), table_name.to_string())
347    }
348}
349
350impl fmt::Display for MySqlTableName {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        write!(
353            f,
354            "{}.{}",
355            quote_identifier(&self.0),
356            quote_identifier(&self.1)
357        )
358    }
359}
360
361impl From<&MySqlTableDesc> for MySqlTableName {
362    fn from(desc: &MySqlTableDesc) -> Self {
363        Self::new(&desc.schema_name, &desc.name)
364    }
365}
366
367#[derive(Debug, Clone, Deserialize, Serialize)]
368pub(crate) struct RewindRequest {
369    /// The output index that should be rewound.
370    pub(crate) output_index: usize,
371    /// The frontier of GTIDs that this snapshot represents; all GTIDs that are not beyond this
372    /// frontier have been committed by the snapshot operator at timestamp 0.
373    pub(crate) snapshot_upper: Antichain<GtidPartition>,
374}
375
376type StackedAsyncOutputHandle<T, D> = AsyncOutputHandle<
377    T,
378    AccountedStackBuilder<CapacityContainerBuilder<TimelyStack<(D, T, Diff)>>>,
379>;
380
381async fn return_definite_error(
382    err: DefiniteError,
383    outputs: &[usize],
384    data_handle: &StackedAsyncOutputHandle<
385        GtidPartition,
386        (usize, Result<SourceMessage, DataflowError>),
387    >,
388    data_cap_set: &CapabilitySet<GtidPartition>,
389    definite_error_handle: &AsyncOutputHandle<
390        GtidPartition,
391        CapacityContainerBuilder<Vec<ReplicationError>>,
392    >,
393    definite_error_cap_set: &CapabilitySet<GtidPartition>,
394) {
395    for output_index in outputs {
396        let update = (
397            (*output_index, Err(err.clone().into())),
398            GtidPartition::new_range(Uuid::minimum(), Uuid::maximum(), GtidState::MAX),
399            Diff::ONE,
400        );
401        data_handle.give_fueled(&data_cap_set[0], update).await;
402    }
403    definite_error_handle.give(
404        &definite_error_cap_set[0],
405        ReplicationError::Definite(Rc::new(err)),
406    );
407    ()
408}
409
410async fn validate_mysql_repl_settings(conn: &mut mysql_async::Conn) -> Result<(), MySqlError> {
411    ensure_gtid_consistency(conn).await?;
412    ensure_full_row_binlog_format(conn).await?;
413    ensure_replication_commit_order(conn).await?;
414
415    Ok(())
416}