Line data Source code
1 : use std::sync::Arc;
2 :
3 : use futures::{FutureExt, TryFutureExt};
4 : use postgres_client::RawCancelToken;
5 : use tokio::io::{AsyncRead, AsyncWrite};
6 : use tokio_util::sync::CancellationToken;
7 : use tracing::{Instrument, debug, error, info};
8 :
9 : use crate::auth::backend::ConsoleRedirectBackend;
10 : use crate::cancellation::{CancelClosure, CancellationHandler};
11 : use crate::config::{ProxyConfig, ProxyProtocolV2};
12 : use crate::context::RequestContext;
13 : use crate::error::ReportableError;
14 : use crate::metrics::{Metrics, NumClientConnectionsGuard};
15 : use crate::pglb::ClientRequestError;
16 : use crate::pglb::handshake::{HandshakeData, handshake};
17 : use crate::pglb::passthrough::ProxyPassthrough;
18 : use crate::protocol2::{ConnectHeader, ConnectionInfo, read_proxy_protocol};
19 : use crate::proxy::{
20 : ErrorSource, connect_compute, forward_compute_params_to_client, send_client_greeting,
21 : };
22 : use crate::util::run_until_cancelled;
23 :
24 0 : pub async fn task_main(
25 0 : config: &'static ProxyConfig,
26 0 : backend: &'static ConsoleRedirectBackend,
27 0 : listener: tokio::net::TcpListener,
28 0 : cancellation_token: CancellationToken,
29 0 : cancellation_handler: Arc<CancellationHandler>,
30 0 : ) -> anyhow::Result<()> {
31 0 : scopeguard::defer! {
32 : info!("proxy has shut down");
33 : }
34 :
35 : // When set for the server socket, the keepalive setting
36 : // will be inherited by all accepted client sockets.
37 0 : socket2::SockRef::from(&listener).set_keepalive(true)?;
38 :
39 0 : let connections = tokio_util::task::task_tracker::TaskTracker::new();
40 0 : let cancellations = tokio_util::task::task_tracker::TaskTracker::new();
41 :
42 0 : while let Some(accept_result) =
43 0 : run_until_cancelled(listener.accept(), &cancellation_token).await
44 : {
45 0 : let (socket, peer_addr) = accept_result?;
46 :
47 0 : let conn_gauge = Metrics::get()
48 0 : .proxy
49 0 : .client_connections
50 0 : .guard(crate::metrics::Protocol::Tcp);
51 :
52 0 : let session_id = uuid::Uuid::new_v4();
53 0 : let cancellation_handler = Arc::clone(&cancellation_handler);
54 0 : let cancellations = cancellations.clone();
55 :
56 0 : debug!(protocol = "tcp", %session_id, "accepted new TCP connection");
57 :
58 0 : connections.spawn(async move {
59 0 : let (socket, conn_info) = match config.proxy_protocol_v2 {
60 : ProxyProtocolV2::Required => {
61 0 : match read_proxy_protocol(socket).await {
62 0 : Err(e) => {
63 0 : error!("per-client task finished with an error: {e:#}");
64 0 : return;
65 : }
66 : // our load balancers will not send any more data. let's just exit immediately
67 0 : Ok((_socket, ConnectHeader::Local)) => {
68 0 : debug!("healthcheck received");
69 0 : return;
70 : }
71 0 : Ok((socket, ConnectHeader::Proxy(info))) => (socket, info),
72 : }
73 : }
74 : // ignore the header - it cannot be confused for a postgres or http connection so will
75 : // error later.
76 0 : ProxyProtocolV2::Rejected => (
77 0 : socket,
78 0 : ConnectionInfo {
79 0 : addr: peer_addr,
80 0 : extra: None,
81 0 : },
82 0 : ),
83 : };
84 :
85 0 : match socket.set_nodelay(true) {
86 0 : Ok(()) => {}
87 0 : Err(e) => {
88 0 : error!(
89 0 : "per-client task finished with an error: failed to set socket option: {e:#}"
90 : );
91 0 : return;
92 : }
93 : }
94 :
95 0 : let ctx = RequestContext::new(session_id, conn_info, crate::metrics::Protocol::Tcp);
96 :
97 0 : let res = handle_client(
98 0 : config,
99 0 : backend,
100 0 : &ctx,
101 0 : cancellation_handler,
102 0 : socket,
103 0 : conn_gauge,
104 0 : cancellations,
105 0 : )
106 0 : .instrument(ctx.span())
107 0 : .boxed()
108 0 : .await;
109 :
110 0 : match res {
111 0 : Err(e) => {
112 0 : ctx.set_error_kind(e.get_error_kind());
113 0 : error!(parent: &ctx.span(), "per-client task finished with an error: {e:#}");
114 : }
115 0 : Ok(None) => {
116 0 : ctx.set_success();
117 0 : }
118 0 : Ok(Some(p)) => {
119 0 : ctx.set_success();
120 0 : let _disconnect = ctx.log_connect();
121 0 : match p.proxy_pass().await {
122 0 : Ok(()) => {}
123 0 : Err(ErrorSource::Client(e)) => {
124 0 : error!(
125 : ?session_id,
126 0 : "per-client task finished with an IO error from the client: {e:#}"
127 : );
128 : }
129 0 : Err(ErrorSource::Compute(e)) => {
130 0 : error!(
131 : ?session_id,
132 0 : "per-client task finished with an IO error from the compute: {e:#}"
133 : );
134 : }
135 : }
136 : }
137 : }
138 0 : });
139 : }
140 :
141 0 : connections.close();
142 0 : cancellations.close();
143 0 : drop(listener);
144 :
145 : // Drain connections
146 0 : connections.wait().await;
147 0 : cancellations.wait().await;
148 :
149 0 : Ok(())
150 0 : }
151 :
152 : #[allow(clippy::too_many_arguments)]
153 0 : pub(crate) async fn handle_client<S: AsyncRead + AsyncWrite + Unpin + Send>(
154 0 : config: &'static ProxyConfig,
155 0 : backend: &'static ConsoleRedirectBackend,
156 0 : ctx: &RequestContext,
157 0 : cancellation_handler: Arc<CancellationHandler>,
158 0 : stream: S,
159 0 : conn_gauge: NumClientConnectionsGuard<'static>,
160 0 : cancellations: tokio_util::task::task_tracker::TaskTracker,
161 0 : ) -> Result<Option<ProxyPassthrough<S>>, ClientRequestError> {
162 0 : debug!(
163 0 : protocol = %ctx.protocol(),
164 0 : "handling interactive connection from client"
165 : );
166 :
167 0 : let metrics = &Metrics::get().proxy;
168 0 : let proto = ctx.protocol();
169 0 : let request_gauge = metrics.connection_requests.guard(proto);
170 :
171 0 : let tls = config.tls_config.load();
172 0 : let tls = tls.as_deref();
173 :
174 0 : let record_handshake_error = !ctx.has_private_peer_addr();
175 0 : let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Client);
176 0 : let do_handshake = handshake(ctx, stream, tls, record_handshake_error);
177 :
178 0 : let (mut stream, params) = match tokio::time::timeout(config.handshake_timeout, do_handshake)
179 0 : .await??
180 : {
181 0 : HandshakeData::Startup(stream, params) => (stream, params),
182 0 : HandshakeData::Cancel(cancel_key_data) => {
183 : // spawn a task to cancel the session, but don't wait for it
184 0 : cancellations.spawn({
185 0 : let cancellation_handler_clone = Arc::clone(&cancellation_handler);
186 0 : let ctx = ctx.clone();
187 0 : let cancel_span = tracing::span!(parent: None, tracing::Level::INFO, "cancel_session", session_id = ?ctx.session_id());
188 0 : cancel_span.follows_from(tracing::Span::current());
189 0 : async move {
190 0 : cancellation_handler_clone
191 0 : .cancel_session(
192 0 : cancel_key_data,
193 0 : ctx,
194 0 : config.authentication_config.ip_allowlist_check_enabled,
195 0 : config.authentication_config.is_vpc_acccess_proxy,
196 0 : backend.get_api(),
197 0 : )
198 0 : .await
199 0 : .inspect_err(|e | debug!(error = ?e, "cancel_session failed")).ok();
200 0 : }.instrument(cancel_span)
201 : });
202 :
203 0 : return Ok(None);
204 : }
205 : };
206 0 : drop(pause);
207 :
208 0 : ctx.set_db_options(params.clone());
209 :
210 0 : let (node_info, mut auth_info, user_info) = match backend
211 0 : .authenticate(ctx, &config.authentication_config, &mut stream)
212 0 : .await
213 : {
214 0 : Ok(auth_result) => auth_result,
215 0 : Err(e) => Err(stream.throw_error(e, Some(ctx)).await)?,
216 : };
217 0 : auth_info.set_startup_params(¶ms, true);
218 :
219 0 : let mut node = connect_compute::connect_to_compute(
220 0 : ctx,
221 0 : config,
222 0 : &node_info,
223 0 : connect_compute::TlsNegotiation::Postgres,
224 : )
225 0 : .or_else(|e| async { Err(stream.throw_error(e, Some(ctx)).await) })
226 0 : .await?;
227 :
228 0 : auth_info
229 0 : .authenticate(ctx, &mut node)
230 0 : .or_else(|e| async { Err(stream.throw_error(e, Some(ctx)).await) })
231 0 : .await?;
232 0 : send_client_greeting(ctx, &config.greetings, &mut stream);
233 :
234 0 : let session = cancellation_handler.get_key();
235 :
236 0 : let (process_id, secret_key) =
237 0 : forward_compute_params_to_client(ctx, *session.key(), &mut stream, &mut node.stream)
238 0 : .await?;
239 0 : let stream = stream.flush_and_into_inner().await?;
240 0 : let hostname = node.hostname.to_string();
241 :
242 0 : let session_id = ctx.session_id();
243 0 : let (cancel_on_shutdown, cancel) = tokio::sync::oneshot::channel();
244 0 : tokio::spawn(async move {
245 0 : session
246 0 : .maintain_cancel_key(
247 0 : session_id,
248 0 : cancel,
249 0 : &CancelClosure {
250 0 : socket_addr: node.socket_addr,
251 0 : cancel_token: RawCancelToken {
252 0 : ssl_mode: node.ssl_mode,
253 0 : process_id,
254 0 : secret_key,
255 0 : },
256 0 : hostname,
257 0 : user_info,
258 0 : },
259 0 : &config.connect_to_compute,
260 0 : )
261 0 : .await;
262 0 : });
263 :
264 0 : Ok(Some(ProxyPassthrough {
265 0 : client: stream,
266 0 : compute: node.stream.into_framed().into_inner(),
267 0 :
268 0 : aux: node.aux,
269 0 : private_link_id: None,
270 0 :
271 0 : _cancel_on_shutdown: cancel_on_shutdown,
272 0 :
273 0 : _req: request_gauge,
274 0 : _conn: conn_gauge,
275 0 : _db_conn: node.guage,
276 0 : }))
277 0 : }
|