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