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