Skip to main content

servers/postgres/
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 ::auth::UserProviderRef;
21use async_trait::async_trait;
22use catalog::process_manager::ProcessManagerRef;
23use common_runtime::Runtime;
24use common_runtime::runtime::RuntimeTrait;
25use common_telemetry::{debug, warn};
26use futures::StreamExt;
27use pgwire::tokio::process_socket;
28use tokio_rustls::TlsAcceptor;
29
30use crate::batcher::logical_table::LogicalTablePendingRowsBatcher;
31use crate::error::Result;
32use crate::postgres::{MakePostgresServerHandler, MakePostgresServerHandlerBuilder};
33use crate::prom_remote_write::validation::PromValidationMode;
34use crate::query_handler::CopyInHandlerRef;
35use crate::query_handler::InfluxdbLineProtocolHandlerRef;
36use crate::query_handler::OpenTelemetryProtocolHandlerRef;
37use crate::query_handler::PipelineHandlerRef;
38use crate::query_handler::PromStoreProtocolHandlerRef;
39use crate::query_handler::sql::ServerSqlQueryHandlerRef;
40use crate::request_memory_limiter::ServerMemoryLimiter;
41use crate::server::{AbortableStream, BaseTcpServer, Server};
42use crate::tls::ReloadableTlsServerConfig;
43
44pub struct PostgresServer {
45    base_server: BaseTcpServer,
46    make_handler: Arc<MakePostgresServerHandler>,
47    tls_server_config: Arc<ReloadableTlsServerConfig>,
48    keep_alive_secs: u64,
49    batching_enabled: bool,
50    influxdb_handler: Option<InfluxdbLineProtocolHandlerRef>,
51    otlp_handler: Option<OpenTelemetryProtocolHandlerRef>,
52    otlp_with_metric_engine: bool,
53    memory_limiter: ServerMemoryLimiter,
54    prom_write_state: Option<crate::http::prom_store::PromStoreState>,
55    bind_addr: Option<SocketAddr>,
56    process_manager: Option<ProcessManagerRef>,
57}
58
59impl PostgresServer {
60    /// Creates a new Postgres server with provided query_handler and async runtime.
61    ///
62    /// `query_handler` and `copy_in_handler` are expected to be handles to
63    /// the same frontend instance (the SQL and COPY FROM STDIN facets of
64    /// one object); they are separate parameters only because they are
65    /// separate traits.
66    #[allow(clippy::too_many_arguments)]
67    pub fn new(
68        query_handler: ServerSqlQueryHandlerRef,
69        copy_in_handler: CopyInHandlerRef,
70        force_tls: bool,
71        tls_server_config: Arc<ReloadableTlsServerConfig>,
72        keep_alive_secs: u64,
73        io_runtime: Runtime,
74        user_provider: Option<UserProviderRef>,
75        process_manager: Option<ProcessManagerRef>,
76    ) -> PostgresServer {
77        let make_handler = Arc::new(
78            MakePostgresServerHandlerBuilder::default()
79                .query_handler(query_handler.clone())
80                .copy_in_handler(copy_in_handler)
81                .user_provider(user_provider.clone())
82                .force_tls(force_tls)
83                .build()
84                .unwrap(),
85        );
86        PostgresServer {
87            base_server: BaseTcpServer::create_server("Postgres", io_runtime),
88            make_handler,
89            tls_server_config,
90            keep_alive_secs,
91            batching_enabled: false,
92            influxdb_handler: None,
93            otlp_handler: None,
94            otlp_with_metric_engine: false,
95            memory_limiter: ServerMemoryLimiter::default(),
96            prom_write_state: None,
97            bind_addr: None,
98            process_manager,
99        }
100    }
101
102    /// Enables ordinary-table batching for connections accepted by this server.
103    pub fn with_batching_enabled(mut self, enabled: bool) -> Self {
104        self.batching_enabled = enabled;
105        self
106    }
107
108    /// Sets the shared memory limiter used for OTLP exemplar expansion.
109    pub fn with_memory_limiter(mut self, limiter: ServerMemoryLimiter) -> Self {
110        self.memory_limiter = limiter;
111        self
112    }
113
114    /// Wires the influxdb line-protocol handler used by table-less
115    /// `COPY FROM STDIN WITH (FORMAT influxdb)` flushes — the same
116    /// handler the HTTP influxdb write endpoints use, so a flushed batch
117    /// runs through the identical pipeline.
118    pub fn with_influxdb_handler(mut self, handler: InfluxdbLineProtocolHandlerRef) -> Self {
119        self.influxdb_handler = Some(handler);
120        self
121    }
122
123    /// Wires the OTLP handler used by
124    /// `COPY [table] FROM STDIN WITH (FORMAT otlp)` — the same handler the
125    /// OTLP/HTTP endpoints use, so the payload runs through the
126    /// identical pipeline. `with_metric_engine` carries the same flag
127    /// the HTTP wiring passes from its options.
128    pub fn with_otlp_handler(
129        mut self,
130        handler: OpenTelemetryProtocolHandlerRef,
131        with_metric_engine: bool,
132    ) -> Self {
133        self.otlp_handler = Some(handler);
134        self.otlp_with_metric_engine = with_metric_engine;
135        self
136    }
137
138    /// Wires the Prometheus Remote Write ingestion used by table-less
139    /// `COPY FROM STDIN WITH (FORMAT promwrite)` — the same handler,
140    /// metric-engine flag, validation mode and optional shared logical-table
141    /// batcher the HTTP endpoint's state carries.
142    pub fn with_prom_remote_write(
143        mut self,
144        handler: PromStoreProtocolHandlerRef,
145        pipeline_handler: Option<PipelineHandlerRef>,
146        with_metric_engine: bool,
147        validation_mode: PromValidationMode,
148        pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
149    ) -> Self {
150        self.prom_write_state = Some(crate::http::prom_store::PromStoreState {
151            prom_store_handler: handler,
152            pipeline_handler,
153            prom_store_with_metric_engine: with_metric_engine,
154            prom_validation_mode: validation_mode,
155            pending_rows_batcher,
156            // Placeholder; `accept` injects the server's shared limiter
157            // (see below) so the receive-stage charging and the
158            // ingestion core enforce ONE budget.
159            memory_limiter: ServerMemoryLimiter::default(),
160        });
161        self
162    }
163
164    fn accept(
165        &self,
166        io_runtime: Runtime,
167        accepting_stream: AbortableStream,
168    ) -> impl Future<Output = ()> + use<> {
169        // Assemble the per-connection handler directly, including any
170        // `with_*` wiring applied after construction (the influxdb
171        // line-protocol handler). Constructing the struct — instead of
172        // going through the builder — keeps this infallible: no
173        // `.build().unwrap()` on the hot accept path.
174        let make_handler = &self.make_handler;
175        // The ingestion state enforces the same shared request-memory
176        // budget (`max_in_flight_write_bytes`) as the HTTP endpoints:
177        // receive-stage COPY buffering and decode/conversion memory are
178        // charged against one limiter.
179        let prom_write_state = self.prom_write_state.clone().map(|mut state| {
180            state.memory_limiter = self.memory_limiter.clone();
181            state
182        });
183        let handler_maker = Arc::new(MakePostgresServerHandler {
184            query_handler: make_handler.query_handler.clone(),
185            copy_in_handler: make_handler.copy_in_handler.clone(),
186            influxdb_handler: self.influxdb_handler.clone(),
187            otlp_handler: self.otlp_handler.clone(),
188            otlp_with_metric_engine: self.otlp_with_metric_engine,
189            memory_limiter: self.memory_limiter.clone(),
190            prom_write_state,
191            user_provider: make_handler.user_provider.clone(),
192            param_provider: make_handler.param_provider.clone(),
193            force_tls: make_handler.force_tls,
194        });
195        let batching_enabled = self.batching_enabled;
196        let tls_server_config = self.tls_server_config.clone();
197        let process_manager = self.process_manager.clone();
198        accepting_stream.for_each(move |tcp_stream| {
199            let io_runtime = io_runtime.clone();
200            let tls_acceptor = tls_server_config.get_config().map(TlsAcceptor::from);
201            let handler_maker = handler_maker.clone();
202            let process_id = process_manager.as_ref().map(|p| p.next_id()).unwrap_or(0);
203
204            async move {
205                match tcp_stream {
206                    Err(error) => debug!("Broken pipe: {}", error), // IoError doesn't impl ErrorExt.
207                    Ok(io_stream) => {
208                        let addr = match io_stream.peer_addr() {
209                            Ok(addr) => {
210                                debug!("PostgreSQL client coming from {}", addr);
211                                Some(addr)
212                            }
213                            Err(e) => {
214                                warn!(e; "Failed to get PostgreSQL client addr");
215                                None
216                            }
217                        };
218
219                        let _handle = io_runtime.spawn(async move {
220                            crate::metrics::METRIC_POSTGRES_CONNECTIONS.inc();
221                            let pg_handler =
222                                Arc::new(handler_maker.make(addr, process_id, batching_enabled));
223                            let r =
224                                process_socket(io_stream, tls_acceptor.clone(), pg_handler).await;
225                            crate::metrics::METRIC_POSTGRES_CONNECTIONS.dec();
226                            r
227                        });
228                    }
229                };
230            }
231        })
232    }
233}
234
235pub const POSTGRES_SERVER: &str = "POSTGRES_SERVER";
236
237#[async_trait]
238impl Server for PostgresServer {
239    async fn shutdown(&self) -> Result<()> {
240        self.base_server.shutdown().await
241    }
242
243    async fn start(&mut self, listening: SocketAddr) -> Result<()> {
244        let (stream, addr) = self
245            .base_server
246            .bind(listening, self.keep_alive_secs)
247            .await?;
248
249        let io_runtime = self.base_server.io_runtime();
250        let join_handle = common_runtime::spawn_global(self.accept(io_runtime, stream));
251
252        self.base_server.start_with(join_handle).await?;
253
254        self.bind_addr = Some(addr);
255        Ok(())
256    }
257
258    fn name(&self) -> &str {
259        POSTGRES_SERVER
260    }
261
262    fn bind_addr(&self) -> Option<SocketAddr> {
263        self.bind_addr
264    }
265
266    fn as_any(&self) -> &dyn Any {
267        self
268    }
269}