1use mysql_async::{Conn, Opts, OptsBuilder};
11use std::collections::BTreeSet;
12use std::future::Future;
13use std::net::IpAddr;
14use std::ops::{Deref, DerefMut};
15use std::panic::AssertUnwindSafe;
16use std::pin::Pin;
17use std::time::Duration;
18
19use mz_aws_util::rds::RdsIamAuth;
20use mz_ore::future::{InTask, OreFutureExt, TimeoutError};
21use mz_ore::option::OptionExt;
22use mz_ore::task::spawn;
23use mz_repr::CatalogItemId;
24use mz_ssh_util::tunnel::{SshTimeoutConfig, SshTunnelConfig};
25use mz_ssh_util::tunnel_manager::{ManagedSshTunnelHandle, SshTunnelManager};
26use serde::{Deserialize, Serialize};
27use tracing::{error, info, warn};
28
29use crate::MySqlError;
30
31#[derive(Debug, PartialEq, Clone)]
34pub enum TunnelConfig {
35 Direct {
39 resolved_ips: Option<BTreeSet<IpAddr>>,
40 },
41 Ssh { config: SshTunnelConfig },
47 AwsPrivatelink {
50 connection_id: CatalogItemId,
52 },
53}
54
55pub const DEFAULT_TCP_KEEPALIVE: Duration = Duration::from_secs(60);
56pub const DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME: Duration = Duration::ZERO;
57pub const DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT: Duration = Duration::from_secs(3600);
58pub const DEFAULT_SNAPSHOT_WAIT_TIMEOUT: Duration = Duration::from_secs(48 * 60 * 60);
61pub const MIN_SNAPSHOT_WAIT_TIMEOUT: Duration = Duration::from_secs(1);
63pub const MAX_SNAPSHOT_WAIT_TIMEOUT: Duration = Duration::from_secs(2147483);
66pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
67
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub struct TimeoutConfig {
70 pub snapshot_max_execution_time: Option<Duration>,
72 pub snapshot_lock_wait_timeout: Option<Duration>,
73 pub snapshot_wait_timeout: Option<Duration>,
74
75 pub tcp_keepalive: Option<Duration>,
77
78 pub connect_timeout: Option<Duration>,
82 }
86
87impl Default for TimeoutConfig {
88 fn default() -> Self {
89 Self {
90 snapshot_max_execution_time: Some(DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME),
91 snapshot_lock_wait_timeout: Some(DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT),
92 snapshot_wait_timeout: Some(DEFAULT_SNAPSHOT_WAIT_TIMEOUT),
93 tcp_keepalive: Some(DEFAULT_TCP_KEEPALIVE),
94 connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
95 }
96 }
97}
98
99impl TimeoutConfig {
100 pub fn build(
101 snapshot_max_execution_time: Duration,
102 snapshot_lock_wait_timeout: Duration,
103 snapshot_wait_timeout: Duration,
104 tcp_keepalive: Duration,
105 connect_timeout: Duration,
106 ) -> Self {
107 let snapshot_lock_wait_timeout = if snapshot_lock_wait_timeout.as_secs() > 31536000 {
113 error!(
114 "snapshot_lock_wait_timeout is too large: {}. Maximum is 31536000.",
115 snapshot_lock_wait_timeout.as_secs()
116 );
117 Some(DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT)
118 } else {
119 Some(snapshot_lock_wait_timeout)
120 };
121
122 let snapshot_wait_timeout = if snapshot_wait_timeout > MAX_SNAPSHOT_WAIT_TIMEOUT
124 || snapshot_wait_timeout < MIN_SNAPSHOT_WAIT_TIMEOUT
125 {
126 error!(
127 "snapshot_wait_timeout is out of range: {}. Must be within [{}, {}].",
128 snapshot_wait_timeout.as_secs(),
129 MIN_SNAPSHOT_WAIT_TIMEOUT.as_secs(),
130 MAX_SNAPSHOT_WAIT_TIMEOUT.as_secs(),
131 );
132 Some(DEFAULT_SNAPSHOT_WAIT_TIMEOUT)
133 } else {
134 Some(snapshot_wait_timeout)
135 };
136
137 let snapshot_max_execution_time = if snapshot_max_execution_time.as_millis() > 4294967295 {
139 error!(
140 "snapshot_max_execution_time is too large: {}. Maximum is 4294967295.",
141 snapshot_max_execution_time.as_secs()
142 );
143 Some(DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME)
144 } else {
145 Some(snapshot_max_execution_time)
146 };
147
148 let tcp_keepalive = match u32::try_from(tcp_keepalive.as_millis()) {
149 Err(_) => {
150 error!(
151 "tcp_keepalive is too large: {}. Maximum is {}.",
152 tcp_keepalive.as_millis(),
153 u32::MAX,
154 );
155 Some(DEFAULT_TCP_KEEPALIVE)
156 }
157 Ok(_) => Some(tcp_keepalive),
158 };
159
160 let connect_timeout = match u32::try_from(connect_timeout.as_millis()) {
161 Err(_) => {
162 error!(
163 "connect_timeout is too large: {}. Maximum is {}.",
164 connect_timeout.as_millis(),
165 u32::MAX,
166 );
167 Some(DEFAULT_CONNECT_TIMEOUT)
168 }
169 Ok(_) => Some(connect_timeout),
170 };
171
172 Self {
173 snapshot_max_execution_time,
174 snapshot_lock_wait_timeout,
175 snapshot_wait_timeout,
176 tcp_keepalive,
177 connect_timeout,
178 }
179 }
180
181 pub fn apply_to_opts(&self, mut opts_builder: OptsBuilder) -> Result<OptsBuilder, MySqlError> {
183 if let Some(tcp_keepalive) = self.tcp_keepalive {
184 opts_builder = opts_builder.tcp_keepalive(Some(tcp_keepalive));
185 }
186 Ok(opts_builder)
187 }
188}
189
190#[derive(Debug)]
196pub struct MySqlConn {
197 conn: Conn,
198 _ssh_tunnel_handle: Option<ManagedSshTunnelHandle>,
199}
200
201impl Deref for MySqlConn {
202 type Target = Conn;
203
204 fn deref(&self) -> &Self::Target {
205 &self.conn
206 }
207}
208
209impl DerefMut for MySqlConn {
210 fn deref_mut(&mut self) -> &mut Self::Target {
211 &mut self.conn
212 }
213}
214
215impl MySqlConn {
216 pub async fn disconnect(mut self) -> Result<(), MySqlError> {
217 self.conn.disconnect().await?;
218 self._ssh_tunnel_handle.take();
219 Ok(())
220 }
221
222 pub fn take(self) -> (Conn, Option<ManagedSshTunnelHandle>) {
223 (self.conn, self._ssh_tunnel_handle)
224 }
225}
226
227#[derive(Clone, Debug)]
232pub struct Config {
233 inner: Opts,
234 tunnel: TunnelConfig,
235 in_task: InTask,
239 ssh_timeout_config: SshTimeoutConfig,
240 mysql_timeout_config: TimeoutConfig,
241 iam_auth: Option<RdsIamAuth>,
242}
243
244impl Config {
245 pub fn new(
246 builder: OptsBuilder,
247 tunnel: TunnelConfig,
248 ssh_timeout_config: SshTimeoutConfig,
249 in_task: InTask,
250 mysql_timeout_config: TimeoutConfig,
251 iam_auth: Option<RdsIamAuth>,
252 ) -> Result<Self, MySqlError> {
253 let opts = mysql_timeout_config.apply_to_opts(builder)?;
254 Ok(Self {
255 inner: opts.into(),
256 tunnel,
257 in_task,
258 ssh_timeout_config,
259 mysql_timeout_config,
260 iam_auth,
261 })
262 }
263
264 pub async fn connect(
265 &self,
266 task_name: &str,
267 ssh_tunnel_manager: &SshTunnelManager,
268 ) -> Result<MySqlConn, MySqlError> {
269 let address = format!(
270 "mysql:://{}@{}:{}/{}",
271 self.inner.user().display_or("<unknown-user>"),
272 self.inner.ip_or_hostname(),
273 self.inner.tcp_port(),
274 self.inner.db_name().display_or("<unknown-dbname>"),
275 );
276 info!(%task_name, %address, "connecting");
277 match self.connect_internal(ssh_tunnel_manager).await {
278 Ok(t) => {
279 info!(%task_name, %address, "connected");
280 Ok(t)
281 }
282 Err(e) => {
283 warn!(%task_name, %address, "connection failed: {e:#}");
284 Err(e)
285 }
286 }
287 }
288
289 fn address(&self) -> (&str, u16) {
290 (self.inner.ip_or_hostname(), self.inner.tcp_port())
291 }
292
293 async fn connect_internal(
294 &self,
295 ssh_tunnel_manager: &SshTunnelManager,
296 ) -> Result<MySqlConn, MySqlError> {
297 let mut opts_builder = OptsBuilder::from_opts(self.inner.clone());
298
299 let iam_token = match &self.iam_auth {
300 None => None,
301 Some(iam_auth) => {
302 let (host, port) = self.address();
303 let username = self.inner.user().expect("MySQL: username required");
304
305 let token = iam_auth.token(host, port, username).await?;
306 opts_builder = opts_builder
310 .pass(Some(token.token.unsecure()))
311 .enable_cleartext_plugin(true);
312 Some(token)
313 }
314 };
315
316 let result = self
317 .connect_with_opts(opts_builder, ssh_tunnel_manager)
318 .await;
319 if let Err(error) = &result
320 && let Some(iam_auth) = &self.iam_auth
321 && let Some(token) = &iam_token
322 && is_authentication_failure(error)
323 {
324 iam_auth.token_rejected(token);
325 }
326 result
327 }
328
329 async fn connect_with_opts(
330 &self,
331 mut opts_builder: OptsBuilder,
332 ssh_tunnel_manager: &SshTunnelManager,
333 ) -> Result<MySqlConn, MySqlError> {
334 match &self.tunnel {
335 TunnelConfig::Direct { resolved_ips } => {
336 opts_builder = opts_builder.resolved_ips(
337 resolved_ips
338 .clone()
339 .map(|ips| ips.into_iter().collect::<Vec<_>>()),
340 );
341
342 Ok(MySqlConn {
343 conn: self.connect_with_timeout(opts_builder).await?,
344 _ssh_tunnel_handle: None,
345 })
346 }
347 TunnelConfig::Ssh { config } => {
348 let (host, port) = self.address();
349 let tunnel = ssh_tunnel_manager
350 .connect(
351 config.clone(),
352 host,
353 port,
354 self.ssh_timeout_config,
355 self.in_task,
356 )
357 .await
358 .map_err(MySqlError::Ssh)?;
359
360 let tunnel_addr = tunnel.local_addr();
361 opts_builder = opts_builder
364 .ip_or_hostname(tunnel_addr.ip().to_string())
365 .tcp_port(tunnel_addr.port());
366
367 if let Some(ssl_opts) = self.inner.ssl_opts() {
368 if !ssl_opts.skip_domain_validation() {
369 opts_builder = opts_builder.ssl_opts(Some(
373 ssl_opts.clone().with_danger_tls_hostname_override(Some(
374 self.inner.ip_or_hostname().to_string(),
375 )),
376 ));
377 }
378 }
379
380 Ok(MySqlConn {
381 conn: self.connect_with_timeout(opts_builder).await?,
382 _ssh_tunnel_handle: Some(tunnel),
383 })
384 }
385 TunnelConfig::AwsPrivatelink { connection_id } => {
386 let privatelink_host = mz_cloud_resources::vpc_endpoint_name(*connection_id);
387
388 let mut opts_builder = opts_builder.ip_or_hostname(privatelink_host);
391
392 if let Some(ssl_opts) = self.inner.ssl_opts() {
393 if !ssl_opts.skip_domain_validation() {
394 opts_builder = opts_builder.ssl_opts(Some(
398 ssl_opts.clone().with_danger_tls_hostname_override(Some(
399 self.inner.ip_or_hostname().to_string(),
400 )),
401 ));
402 }
403 }
404
405 Ok(MySqlConn {
406 conn: self.connect_with_timeout(opts_builder).await?,
407 _ssh_tunnel_handle: None,
408 })
409 }
410 }
411 }
412
413 async fn connect_with_timeout(
414 &self,
415 opts_builder: OptsBuilder,
416 ) -> Result<mysql_async::Conn, MySqlError> {
417 let connect = async move {
423 match AssertUnwindSafe(Conn::new(opts_builder))
424 .ore_catch_unwind()
425 .await
426 {
427 Ok(result) => result.map_err(MySqlError::from),
428 Err(payload) => {
429 let message = payload
430 .downcast_ref::<&str>()
431 .map(|s| s.to_string())
432 .or_else(|| payload.downcast_ref::<String>().cloned())
433 .unwrap_or_else(|| "unknown panic".to_string());
434 error!("mysql connection attempt panicked: {message}");
435 Err(MySqlError::ConnectionPanicked(message))
436 }
437 }
438 };
439 let connection_future: Pin<Box<dyn Future<Output = Result<Conn, MySqlError>> + Send>> =
440 if let InTask::Yes = self.in_task {
441 Box::pin(spawn(|| "mysql_connect".to_string(), connect).abort_on_drop())
442 } else {
443 Box::pin(connect)
444 };
445
446 if let Some(connect_timeout) = self.mysql_timeout_config.connect_timeout {
447 mz_ore::future::timeout(connect_timeout, connection_future)
448 .await
449 .map_err(|err| match err {
450 TimeoutError::DeadlineElapsed => MySqlError::ConnectionTimeout(connect_timeout),
452 TimeoutError::Inner(e) => e,
453 })
454 } else {
455 connection_future.await
456 }
457 }
458}
459
460const ER_ACCESS_DENIED_ERROR: u16 = 1045;
462
463fn is_authentication_failure(error: &MySqlError) -> bool {
468 match error {
469 MySqlError::MySql(mysql_async::Error::Server(e)) => e.code == ER_ACCESS_DENIED_ERROR,
470 _ => false,
471 }
472}