Skip to main content

servers/mysql/
server.rs

1// Copyright 2023 Greptime Team
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::any::Any;
16use std::future::Future;
17use std::net::SocketAddr;
18use std::sync::Arc;
19
20use async_trait::async_trait;
21use auth::UserProviderRef;
22use catalog::process_manager::ProcessManagerRef;
23use common_runtime::Runtime;
24use common_runtime::runtime::RuntimeTrait;
25use common_telemetry::{debug, warn};
26use futures::StreamExt;
27use opensrv_mysql::{
28    AsyncMysqlIntermediary, IntermediaryOptions, plain_run_with_options, secure_run_with_options,
29};
30use snafu::ensure;
31use tokio;
32use tokio::io::BufWriter;
33use tokio::net::TcpStream;
34use tokio_rustls::rustls::ServerConfig;
35
36use crate::error::{Error, Result, TlsRequiredSnafu};
37use crate::mysql::handler::MysqlInstanceShim;
38use crate::query_handler::sql::ServerSqlQueryHandlerRef;
39use crate::server::{AbortableStream, BaseTcpServer, Server};
40use crate::tls::ReloadableTlsServerConfig;
41
42// Default size of ResultSet write buffer: 100KB
43const DEFAULT_RESULT_SET_WRITE_BUFFER_SIZE: usize = 100 * 1024;
44
45const CLIENT_DISCONNECT_ERROR_KINDS: &[std::io::ErrorKind] = &[
46    std::io::ErrorKind::ConnectionAborted,
47    std::io::ErrorKind::ConnectionReset,
48    std::io::ErrorKind::BrokenPipe,
49];
50
51/// [`MysqlSpawnRef`] stores arc refs
52/// that should be passed to new [`MysqlInstanceShim`]s.
53pub struct MysqlSpawnRef {
54    query_handler: ServerSqlQueryHandlerRef,
55    user_provider: Option<UserProviderRef>,
56}
57
58impl MysqlSpawnRef {
59    pub fn new(
60        query_handler: ServerSqlQueryHandlerRef,
61        user_provider: Option<UserProviderRef>,
62    ) -> MysqlSpawnRef {
63        MysqlSpawnRef {
64            query_handler,
65            user_provider,
66        }
67    }
68
69    fn query_handler(&self) -> ServerSqlQueryHandlerRef {
70        self.query_handler.clone()
71    }
72    fn user_provider(&self) -> Option<UserProviderRef> {
73        self.user_provider.clone()
74    }
75}
76
77/// [`MysqlSpawnConfig`] stores config values
78/// which are used to initialize [`MysqlInstanceShim`]s.
79pub struct MysqlSpawnConfig {
80    // tls config
81    force_tls: bool,
82    tls: Arc<ReloadableTlsServerConfig>,
83    // keep-alive config
84    keep_alive_secs: u64,
85    // other shim config
86    reject_no_database: bool,
87    // prepared statement cache capacity
88    prepared_stmt_cache_size: usize,
89}
90
91impl MysqlSpawnConfig {
92    pub fn new(
93        force_tls: bool,
94        tls: Arc<ReloadableTlsServerConfig>,
95        keep_alive_secs: u64,
96        reject_no_database: bool,
97        prepared_stmt_cache_size: usize,
98    ) -> MysqlSpawnConfig {
99        MysqlSpawnConfig {
100            force_tls,
101            tls,
102            keep_alive_secs,
103            reject_no_database,
104            prepared_stmt_cache_size,
105        }
106    }
107
108    fn tls(&self) -> Option<Arc<ServerConfig>> {
109        self.tls.get_config()
110    }
111}
112
113impl From<&MysqlSpawnConfig> for IntermediaryOptions {
114    fn from(value: &MysqlSpawnConfig) -> Self {
115        IntermediaryOptions {
116            reject_connection_on_dbname_absence: value.reject_no_database,
117            ..Default::default()
118        }
119    }
120}
121
122pub struct MysqlServer {
123    base_server: BaseTcpServer,
124    spawn_ref: Arc<MysqlSpawnRef>,
125    spawn_config: Arc<MysqlSpawnConfig>,
126    bind_addr: Option<SocketAddr>,
127    process_manager: Option<ProcessManagerRef>,
128}
129
130impl MysqlServer {
131    pub fn create_server(
132        io_runtime: Runtime,
133        spawn_ref: Arc<MysqlSpawnRef>,
134        spawn_config: Arc<MysqlSpawnConfig>,
135        process_manager: Option<ProcessManagerRef>,
136    ) -> Box<dyn Server> {
137        Box::new(MysqlServer {
138            base_server: BaseTcpServer::create_server("MySQL", io_runtime),
139            spawn_ref,
140            spawn_config,
141            bind_addr: None,
142            process_manager,
143        })
144    }
145
146    fn accept(
147        &self,
148        io_runtime: Runtime,
149        stream: AbortableStream,
150        process_manager: Option<ProcessManagerRef>,
151    ) -> impl Future<Output = ()> + use<> {
152        let spawn_ref = self.spawn_ref.clone();
153        let spawn_config = self.spawn_config.clone();
154
155        stream.for_each(move |tcp_stream| {
156            let spawn_ref = spawn_ref.clone();
157            let spawn_config = spawn_config.clone();
158            let io_runtime = io_runtime.clone();
159            let process_id = process_manager.as_ref().map(|p| p.next_id()).unwrap_or(8);
160            async move {
161                match tcp_stream {
162                    Err(e) => warn!(e; "Broken pipe"), // IoError doesn't impl ErrorExt.
163                    Ok(io_stream) => {
164                        if let Err(e) = io_stream.set_nodelay(true) {
165                            warn!(e; "Failed to set TCP nodelay");
166                        }
167                        io_runtime.spawn(async move {
168                            if let Err(error) =
169                                Self::handle(io_stream, spawn_ref, spawn_config, process_id).await
170                            {
171                                warn!(error; "Unexpected error when handling TcpStream");
172                            };
173                        });
174                    }
175                };
176            }
177        })
178    }
179
180    async fn handle(
181        stream: TcpStream,
182        spawn_ref: Arc<MysqlSpawnRef>,
183        spawn_config: Arc<MysqlSpawnConfig>,
184        process_id: u32,
185    ) -> Result<()> {
186        debug!("MySQL connection coming from: {}", stream.peer_addr()?);
187        crate::metrics::METRIC_MYSQL_CONNECTIONS.inc();
188        if let Err(e) = Self::do_handle(stream, spawn_ref, spawn_config, process_id).await {
189            if let Error::InternalIo { error } = &e
190                && CLIENT_DISCONNECT_ERROR_KINDS.contains(&error.kind())
191            {
192                // This is a client-side error, we don't need to log it.
193            } else {
194                // TODO(LFC): Write this error to client as well, in MySQL text protocol.
195                // Looks like we have to expose opensrv-mysql's `PacketWriter`?
196                warn!(e; "Internal error occurred during query exec, server actively close the channel to let client try next time");
197            }
198        }
199        crate::metrics::METRIC_MYSQL_CONNECTIONS.dec();
200
201        Ok(())
202    }
203
204    async fn do_handle(
205        stream: TcpStream,
206        spawn_ref: Arc<MysqlSpawnRef>,
207        spawn_config: Arc<MysqlSpawnConfig>,
208        process_id: u32,
209    ) -> Result<()> {
210        let mut shim = MysqlInstanceShim::create(
211            spawn_ref.query_handler(),
212            spawn_ref.user_provider(),
213            stream.peer_addr()?,
214            process_id,
215            spawn_config.prepared_stmt_cache_size,
216        );
217        let (mut r, w) = stream.into_split();
218        let mut w = BufWriter::with_capacity(DEFAULT_RESULT_SET_WRITE_BUFFER_SIZE, w);
219
220        let ops = spawn_config.as_ref().into();
221
222        let (client_tls, init_params) =
223            AsyncMysqlIntermediary::init_before_ssl(&mut shim, &mut r, &mut w, &spawn_config.tls())
224                .await?;
225
226        ensure!(
227            !spawn_config.force_tls || client_tls,
228            TlsRequiredSnafu {
229                server: "mysql".to_owned()
230            }
231        );
232
233        match spawn_config.tls() {
234            Some(tls_conf) if client_tls => {
235                secure_run_with_options(shim, w, ops, tls_conf, init_params).await
236            }
237            _ => plain_run_with_options(shim, w, ops, init_params).await,
238        }
239    }
240}
241
242pub const MYSQL_SERVER: &str = "MYSQL_SERVER";
243
244#[async_trait]
245impl Server for MysqlServer {
246    async fn shutdown(&self) -> Result<()> {
247        self.base_server.shutdown().await
248    }
249
250    async fn start(&mut self, listening: SocketAddr) -> Result<()> {
251        let (stream, addr) = self
252            .base_server
253            .bind(listening, self.spawn_config.keep_alive_secs)
254            .await?;
255        let io_runtime = self.base_server.io_runtime();
256
257        let join_handle = common_runtime::spawn_global(self.accept(
258            io_runtime,
259            stream,
260            self.process_manager.clone(),
261        ));
262        self.base_server.start_with(join_handle).await?;
263
264        self.bind_addr = Some(addr);
265        Ok(())
266    }
267
268    fn name(&self) -> &str {
269        MYSQL_SERVER
270    }
271
272    fn bind_addr(&self) -> Option<SocketAddr> {
273        self.bind_addr
274    }
275
276    fn as_any(&self) -> &dyn Any {
277        self
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::CLIENT_DISCONNECT_ERROR_KINDS;
284
285    #[test]
286    fn test_client_disconnect_error_kinds() {
287        assert!(CLIENT_DISCONNECT_ERROR_KINDS.contains(&std::io::ErrorKind::ConnectionAborted));
288        assert!(CLIENT_DISCONNECT_ERROR_KINDS.contains(&std::io::ErrorKind::ConnectionReset));
289        assert!(CLIENT_DISCONNECT_ERROR_KINDS.contains(&std::io::ErrorKind::BrokenPipe));
290    }
291}